【问题标题】:My app can't open internal storage file我的应用无法打开内部存储文件
【发布时间】:2018-10-11 17:48:25
【问题描述】:

Android 应用程序:内部存储上新创建的文件出现在文件列表中,但尝试打开文件会创建异常“没有这样的文件或目录”。 (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)

已经尝试了许多变体。 任何建议都非常感谢!

【问题讨论】:

  • 您设备上的文件已经存在吗?您需要获取文件的文件路径...而不仅仅是 xxxyyy.txt
  • 有什么理由不使用:input = openFileInput("xxxyyy.txt")?
  • 相关 Commonsware 博文:commonsware.com/blog/2017/11/13/…
  • 您设法解决了这个问题吗?如果有,怎么做?
  • 看下面的答案,添加'GetfilesDir()'完美解决了这个问题。

标签: android file storage internal


【解决方案1】:

如果需要访问使用openFileOutput创建的文件,则需要在创建File对象时指定正确的目录,在这种情况下:

File file = new File(getFilesDir(), "xxxyyy.txt");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 2014-10-03
    • 1970-01-01
    • 2014-10-07
    • 2021-05-06
    相关资源
    最近更新 更多