java - FileReader 上的 FileNotFoundException
问题描述
我的应用程序需要选择一个 .txt 文档,将其打开并逐行阅读。我可以获取文件路径没有问题,但是 FileReader 不会打开文件,抛出 FileNotFoundException。
我的代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK){
Uri uri = data.getData();
filePath = uri.getPath();
if (filePath != ""){
txtvFileSelected.setText(filePath);
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(filePath);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = null;
new BufferedReader(fileReader);
int currentLine = 0;
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
//TODO: add string separation into floats here.
currentLine++;
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("File not found '" + filePath + "'");
} catch (IOException e) {
e.printStackTrace();
}
}
else
txtvFileSelected.setText("No file selected");
}
}
}
}
错误日志:
05-14 09:14:51.409 24212-24279/com.examens.gilian.robotapplication OpenGLRenderer: Initialized EGL, version 1.4
05-14 09:14:53.428 24212-24279/com.examens.gilian.robotapplication D/OpenGLRenderer: endAllActiveAnimators on 0xb8ad5368 (RippleDrawable) with handle 0xb8988670
05-14 09:14:59.046 24212-24212/com.examens.gilian.robotapplication I/System.out: File not found '/document/primary:media/Data.txt'
解决方案
文件路径 = uri.getPath();
那不是文件系统路径,所以难怪什么都找不到。
而是打开一个输入流并从流中读取。
InputStream is = getContentResolver().openInputStream(data.getData());
推荐阅读
- java - mac eclipse 氧气无法导入gnu.io.SerialPort
- javascript - 函数调用不返回控制 AJAX - PHP - MYSQLI
- scala - Scala - 方法执行的顺序
- html - 如何将表元素与引导 v4.1 表中的 td 元素对齐?
- ios - UIPickerView 报告错误的行
- android - ListView with Checkboxes:如何检查它是否被选中?
- c# - 在更改组合框时填充 ListView - 正确的 MVVM 实现
- gluon - gluon-mobile 插件无法处理多版本 jar
- java - 使用 JAXB Marshaller 构建的 StringWrite 在使用 POSTMAN 查看时显示“<”而不是“<”
- android - FCM Push 在 Android 8.0、Oreo 上不起作用