gpt4 book ai didi

java - FileReader 上的 FileNotFoundException

转载 作者:行者123 更新时间:2023-12-02 11:15:19 24 4
gpt4 key购买 nike

我的应用程序需要选择一个.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'

最佳答案

filePath = uri.getPath();

这不是文件系统路径,所以难怪找不到任何东西。

而是打开一个输入流并从流中读取。

InputStream is = getContentResolver().openInputStream(data.getData());

关于java - FileReader 上的 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50324895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com