48

I am a newbie working with Android. A file is already created in the location data/data/myapp/files/hello.txt; the contents of this file is "hello". How do I read the file's content?

newenglander
  • 2,019
  • 24
  • 55
Shan
  • 1,081
  • 1
  • 12
  • 35

6 Answers6

67

Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

To read data from internal storage you need your app files folder and read content from here

String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );

Also you can use this approach

FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    sb.append(line);
}
Marc
  • 3,683
  • 8
  • 34
  • 48
Georgy Gobozov
  • 13,633
  • 8
  • 72
  • 78
10

Read a file as a string full version (handling exceptions, using UTF-8, handling new line):

// Calling:
/* 
    Context context = getApplicationContext();
    String filename = "log.txt";
    String str = read_file(context, filename);
*/  
public String read_file(Context context, String filename) {
        try {
            FileInputStream fis = context.openFileInput(filename);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();
        } catch (FileNotFoundException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
    }

Note: you don't need to bother about file path only with file name.

Skalár Wag
  • 2,247
  • 2
  • 18
  • 21
4

Call To the following function with argument as you file path:

  private String getFileContent(String targetFilePath) {
      File file = new File(targetFilePath);
      try {
        fileInputStream = new FileInputStream(file);
      } catch (FileNotFoundException e) {
        Log.e("", "" + e.printStackTrace());
      }

      StringBuilder sb;
      while (fileInputStream.available() > 0) {
        if (null == sb) {
           sb = new StringBuilder();
        }
        sb.append((char) fileInputStream.read());
      }

      String fileContent;
      if (null != sb) {
        fileContent = sb.toString();
        // This is your file content in String.
      }
      try {
        fileInputStream.close();
      } catch (Exception e) {
        Log.e("", "" + e.printStackTrace());
      }
      return fileContent;
  }
Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
0
    String path = Environment.getExternalStorageDirectory().toString();
    Log.d("Files", "Path: " + path);
    File f = new File(path);
    File file[] = f.listFiles();
    Log.d("Files", "Size: " + file.length);
    for (int i = 0; i < file.length; i++) {
        //here populate your listview
        Log.d("Files", "FileName:" + file[i].getName());

    }
Dmarp
  • 208
  • 1
  • 3
  • 13
0

I prefer to use java.util.Scanner:

try {
    Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
    StringBuilder sb = new StringBuilder();

    while (scanner.hasNext()) {
        sb.append(scanner.next());
    }

    scanner.close();

    String result = sb.toString();

} catch (IOException e) {}
Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63
-1

For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE

try {
            FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
            fos.write(csv.getBytes());
            fos.close();
            File file = Main.this.getFileStreamPath("exported_data.csv");
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
DagW
  • 955
  • 1
  • 15
  • 28
  • 1
    No. The question which was asked concerns *reading* a file, while your code snippet only writes one. – Chris Stratton Apr 24 '15 at 16:03
  • Hey.. The answer is regarding to the mode the file was written in, if its not world readable he will not be able to read it. – DagW Apr 27 '15 at 07:35
  • No, the app which owns the file can of course read it when it is private. It is only other things which won't be able to. – Chris Stratton Apr 27 '15 at 14:46