gpt4 book ai didi

java - 读取 txt 文件时出错

转载 作者:行者123 更新时间:2023-12-02 01:58:20 27 4
gpt4 key购买 nike

当我尝试读取保存在手机外部存储上的文件时,我的代码中出现此错误:

java.io.FileNotFoundException: shopping.txt: open failed: ENOENT (No such file or directory)

我可以成功地将数据写入该文件,我已经做了很多次了。但是,我无法通过提供完整路径或通过其他方法来读取同一文件。

代码写入并保存成功:

File path  = new File(this.getFilesDir().getPath());
String value = "vegetables";
// File output = new File(path + File.separator + fileName);
File output = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
// Toast.makeText(getBaseContext(), "File saved successfully!",
// Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,String.valueOf(output),Toast.LENGTH_LONG).show();
Log.d("MainActivity", "Chemin fichier = [" + output + "]");
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}

编写的代码使我的应用程序崩溃:

try
{
File gFile;
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
//FileInputStream fis = openFileInput("/storage/emulated/0/Android/data/com.example.namour.shoppinglist/files/shopping.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null, input="";
while ((line = reader.readLine()) != null)
input += line;

Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
reader.close();
fis.close();
Toast.makeText(MainActivity.this,"Read successful",Toast.LENGTH_LONG).show();
//return input;
}
catch (IOException e)

{
Log.e("Exception", "File read failed: " + e.toString());
//toast("Error loading file: " + ex.getLocalizedMessage());

}

我做错了什么?当然,不是权限问题,因为我可以成功写入。

非常感谢您的帮助。

最佳答案

您错过了指定正确的路径。您正在当前工作目录(运行时)中查找名为 shopping.txt 的文件。使用正确的路径创建一个新的 File 对象,它将起作用:
文件输入 = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");。您可以通过编写重用您的对象。

关于java - 读取 txt 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52006413/

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