I am new to Android development.
I need to read a text file from the SD card and display that text file. Is there any way to view a text file directly in Android or else how can I read and display the contents of a text file?
If you have an SD card mounted on your device, then you can easily read & write files to the SD card from Office on Android apps. On the Open page, tap This device. Tap SD Card or Documents (SD Card).
Step 1: We will use InputStream to open the file and we will stream the data into it. Step 2: Create a variable to store the size of the file. Step 3: Create a buffer of the size of the file. Step 4: We will read the inputStream file into the buffer.
In your layout you'll need something to display the text. A TextView
is the obvious choice. So you'll have something like this:
<TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
And your code will look like this:
//Find the directory for the SD Card using the API //*Don't* hardcode "/sdcard" File sdcard = Environment.getExternalStorageDirectory(); //Get the text file File file = new File(sdcard,"file.txt"); //Read text from file StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close(); } catch (IOException e) { //You'll need to add proper error handling here } //Find the view by its id TextView tv = (TextView)findViewById(R.id.text_view); //Set the text tv.setText(text);
This could go in the onCreate()
method of your Activity
, or somewhere else depending on just what it is you want to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With