我是一个初学者,正在使用Android。一个文件已经被创建在路径
data/data/myapp/files/hello.txt
下;这个文件的内容为 "hello"。如何读取这个文件的内容?了解如何在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);
}
File.separator
而不是
"/"
。 - milosmnscontext.openFileInput("hello.txt")
,没有第二个参数。 - Nj Subedinew File(context.getFilesDir(), filename)
。 - Omar Aflak读取文件并将其作为字符串返回 (包含异常处理、使用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 "";
}
}
注意:您只需要关心文件名,无需担心文件路径。
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;
}
我更喜欢使用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) {}
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());
}
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();
}
});
}
对于其他人寻找为什么文件无法读取,特别是在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;
}