【发布时间】:2018-08-24 22:52:17
【问题描述】:
当我尝试读取保存在手机外部存储上的文件时,我的代码中出现此错误:
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());
}
我做错了什么? 当然,不是权限问题,因为我可以写成功。
非常感谢您的帮助。
【问题讨论】:
-
这是一个FileNotFoundException,这意味着你正在检查的文件的路径是错误的。
-
在第二段代码中,您没有指定任何父目录。