Shan
Shan

Reputation: 1103

How do I read the file content from the Internal storage - Android App

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?

Upvotes: 50

Views: 172953

Answers (7)

Surajit Roy
Surajit Roy

Reputation: 1

Read a file as a string full version (handling exceptions, handling new line): Just try this code.

try {
                            FileInputStream fis = new FileInputStream(outputFile);
                            byte[] buffer = new byte[1024];
                            int bytesRead;
                            StringBuilder certificateData = new StringBuilder();
                            while ((bytesRead = fis.read(buffer)) != -1) {
                                certificateData.append(new String(buffer, 0, bytesRead));
                            }
                            fis.close();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "Downloaded and read from "+outputFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        } catch (IOException e) {
                            // Handle any errors that may occur while reading the file
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

Upvotes: 0

Shridutt Kothari
Shridutt Kothari

Reputation: 7394

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;
  }

Upvotes: 4

Georgy Gobozov
Georgy Gobozov

Reputation: 13731

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);
}

Upvotes: 68

Hafez Divandari
Hafez Divandari

Reputation: 9059

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) {}

Upvotes: 0

Dmarp
Dmarp

Reputation: 228

    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());

    }

Upvotes: 0

DagW
DagW

Reputation: 955

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;
        }

Upvotes: -1

Skal&#225;r Wag
Skal&#225;r Wag

Reputation: 2396

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.

Upvotes: 10

Related Questions