我的应用无法打开内部存储文件
My app can't open internal storage file
Android 应用程序:内部存储上新创建的文件出现在文件列表中,但尝试打开文件会产生异常'No such file or directory'。 (Android 8.0,在多个设备上测试。)
//create a file in internal storage
FileOutputStream output = null;
output = openFileOutput("xxxyyy.txt", Context.MODE_PRIVATE);
String str = "Just any string";
byte[] bytes = str.getBytes();
output.write(bytes, 0, bytes.length);
output.close();
//list the files
String lst[] = fileList();
for (int i = 0; i < lst.length; i++)
{ Log.v("MM" , "INTERNAL FILES: "+lst[i]); }
//system reply: INTERNAL FILES: xxxyyy.txt, ......
//check if file exists and try to open it for reading
File file = new File("xxxyyy.txt");
Log.v("XX" , "TEST: file exists? " + file.exists());
//system reply: TEST: file exists? false
//try to open it for reading
FileInputStream input = null;
try {
input = new FileInputStream("xxxyyy.txt");
} catch (IOException e) {
Log.v("XX" , "TEST: " + e.getMessage());
}
//system reply: TEST: xxxyyy.txt (No such file or directory)
已经尝试了很多变化。
非常感谢任何建议!
如果您需要访问使用 openFileOutput
创建的文件,您需要在创建 File
对象时指定正确的目录,在这种情况下:
File file = new File(getFilesDir(), "xxxyyy.txt");
Android 应用程序:内部存储上新创建的文件出现在文件列表中,但尝试打开文件会产生异常'No such file or directory'。 (Android 8.0,在多个设备上测试。)
//create a file in internal storage
FileOutputStream output = null;
output = openFileOutput("xxxyyy.txt", Context.MODE_PRIVATE);
String str = "Just any string";
byte[] bytes = str.getBytes();
output.write(bytes, 0, bytes.length);
output.close();
//list the files
String lst[] = fileList();
for (int i = 0; i < lst.length; i++)
{ Log.v("MM" , "INTERNAL FILES: "+lst[i]); }
//system reply: INTERNAL FILES: xxxyyy.txt, ......
//check if file exists and try to open it for reading
File file = new File("xxxyyy.txt");
Log.v("XX" , "TEST: file exists? " + file.exists());
//system reply: TEST: file exists? false
//try to open it for reading
FileInputStream input = null;
try {
input = new FileInputStream("xxxyyy.txt");
} catch (IOException e) {
Log.v("XX" , "TEST: " + e.getMessage());
}
//system reply: TEST: xxxyyy.txt (No such file or directory)
已经尝试了很多变化。 非常感谢任何建议!
如果您需要访问使用 openFileOutput
创建的文件,您需要在创建 File
对象时指定正确的目录,在这种情况下:
File file = new File(getFilesDir(), "xxxyyy.txt");