Android - Read text file in sdcard

Using the code below, you can read text files, subtitle files, ... in sdcard.

To get the sdcard directory:

File sdcard = Environment.getExternalStorageDirectory();

File reader function:
public static String readSavedData(Context context, String path) {

 if (fileExistsInSD(path) == false) {
  return "";
 }

 //Get the text file
 File file = new File(path);

 //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');
  }
 } catch (IOException e) {
  return "";
 } catch (Exception e) {
  return "";
 }
 return text.toString(); 
}

The function check file exist in sdcard here.

Leave a Reply

Powered by Blogger.