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

Sha*_*han 41 android internal

我是一名使用Android的新手.已在该位置创建文件data/data/myapp/files/hello.txt; 这个文件的内容是"你好".我如何阅读文件的内容?

Geo*_*zov 59

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

要从内部存储中读取数据,您需要使用app文件夹并从此处读取内容

String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );
Run Code Online (Sandbox Code Playgroud)

你也可以使用这种方法

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意确保它适用的位置,但File类中有一个分隔符字符串.我想你应该使用`File.separator`而不是``/"` (4认同)
  • 正确的函数是`context.openFileInput("hello.txt")`.没有第二个参数. (4认同)

Ska*_*Wag 8

将文件读取为字符串完整版(处理异常,使用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 "";
        }
    }
Run Code Online (Sandbox Code Playgroud)

注意:您不需要仅使用文件名来处理文件路径.