Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a text file from the SD card in Android?

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?

like image 891
RSSS Avatar asked May 25 '10 07:05

RSSS


People also ask

How do I view files on my SD card?

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).

How do I read files on Android?

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.


1 Answers

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.

like image 154
Dave Webb Avatar answered Sep 23 '22 08:09

Dave Webb