如何从内部存储读取文件内容 - Android App

问题描述 投票:0回答:7

我是一名使用 Android 的新手。已在位置

data/data/myapp/files/hello.txt
创建了一个文件;该文件的内容是“hello”。如何读取文件内容?

android internal
7个回答
67
投票

看看如何在 android 中使用存储http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

要从内部存储读取数据,您需要应用程序文件夹并从此处读取内容

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

你也可以使用这个方法

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

10
投票

将文件读取为字符串完整版本(处理异常、使用 UTF-8、处理新行):

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

注意:您不需要只关心文件路径和文件名。


4
投票

使用参数作为文件路径调用以下函数:

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

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

    }

0
投票

我更喜欢使用

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

0
投票

将文件作为字符串完整版本读取(处理异常、处理新行):只需尝试此代码即可。

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

-1
投票

对于其他寻找文件为什么不可读(尤其是在 SD 卡上)的答案的人,请首先像这样写入文件。.注意 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;
        }
© www.soinside.com 2019 - 2024. All rights reserved.