我是一名使用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)
将文件读取为字符串完整版(处理异常,使用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)
注意:您不需要仅使用文件名来处理文件路径.
归档时间: |
|
查看次数: |
121820 次 |
最近记录: |