In this post we will see how we can read the text file from storage in Android. The app will have a simple option to select the text file and display its text content on a Android TextView. The textView
will be having a scrollbar just in case if the text is longer. So let’s start.
Create a layout file in your Android project as below:
res > layout > activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:orientation="vertical"> <TextView android:id="@+id/txtView" android:layout_width="match_parent" android:layout_height="500dp" android:layout_gravity="start" android:layout_margin="5dp" android:gravity="start" android:padding="5dp" android:overScrollMode="always" android:scrollbars="vertical" android:textColor="#000" /> <Button android:id="@+id/btnChooseFile" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="Choose a File" android:background="#3D5AFE" android:textColor="#fff"/> </LinearLayout>
The design is pretty simple with only one Android textView and a button control. When the user will click on the button, the file picker will be opening up using which Text file can be selected.
Now edit the MainActivity
class file as below.
MainActivity.java:
package app.parallelcodes.textreader; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.InputStream; public class MainActivity extends AppCompatActivity { Button btnChooseAFile; TextView txtView; private static final int READ_REQUEST_CODE = 42; ActivityResultLauncher<Intent> filePicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnChooseAFile = findViewById(R.id.btnChooseFile); txtView = findViewById(R.id.txtView); txtView.setMovementMethod(new ScrollingMovementMethod()); filePicker = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK) { Intent intent1 = result.getData(); Uri uri = intent1.getData(); byte[] byteData = getBytes(MainActivity.this, uri); txtView.setText(new String(byteData)); } }); btnChooseAFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ChooseFile(); } }); } public void ChooseFile() { try { Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT); fileIntent.addCategory(Intent.CATEGORY_OPENABLE); fileIntent.setType("text/*"); filePicker.launch(fileIntent); } catch (Exception ex) { Log.e("Error", ex.getMessage()); Toast.makeText(MainActivity.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show(); } } byte[] getBytes(Context context, Uri uri) { InputStream inputStream = null; try { inputStream = context.getContentResolver().openInputStream(uri); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } return outputStream.toByteArray(); } catch (Exception ex) { Log.e("Error", ex.getMessage().toString()); Toast.makeText(context, "getBytes error:" + ex.getMessage(), Toast.LENGTH_LONG).show(); return null; } } }
My Android Manifest file:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.parallelcodes.textreader"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.TextReader" > <activity android:name=".MainActivity" android:exported="true" android:label="@string/app_name" android:theme="@style/Theme.TextReader"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Now run the app. I have tested this on Android 11 and 9, it works without any problems or issues. Please let me know on our Facebook Page if you face any issues.
You can download the source code for free from below link.
DOWNLOAD SOURCE CODE