如何从内部存储读取文件内容 - Android应用程序

49
我是一个初学者,正在使用Android。一个文件已经被创建在路径 data/data/myapp/files/hello.txt 下;这个文件的内容为 "hello"。如何读取这个文件的内容?

1
你可以在Android中使用通常的Java File读取方法来读取文件。 - Rahul
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);
}

1
如果文件是图像,如何处理? - Muhammad Babar
4
不确定这适用于哪里,但是在File类中有一个分隔符字符串。我猜你应该使用 File.separator 而不是 "/" - milosmns
4
正确的函数是 context.openFileInput("hello.txt"),没有第二个参数。 - Nj Subedi
我收到了错误信息:java.lang.IllegalArgumentException: 文件 /data/data/com.example.main/cache/test.conf 包含路径分隔符。 - Dr.jacky
1
还有这个构造函数:new File(context.getFilesDir(), filename) - Omar Aflak
显示剩余5条评论

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

请格式化您的代码。 - CodeSun
请格式化您的代码 - undefined
1
格式化代码 - Shridutt Kothari

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

    }

3
问题规定了“内部”存储。 - Bryan Bryce

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

根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,帮助其他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined

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

1
不。所提出的问题涉及读取文件,而您的代码片段只写入一个文件。 - Chris Stratton
嘿..答案与文件的写入模式有关,如果它不是可读取的,则他将无法阅读它。 - DagW
不,拥有该文件的应用程序在其为私有时当然可以读取它。只有其他东西无法读取。 - Chris Stratton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接