【问题标题】:Android file exists problemsAndroid文件存在问题
【发布时间】:2013-09-13 10:47:41
【问题描述】:

当我制作 File file = new File(etc..) 时,我实际上在 SD 卡上创建了该文件?我有点困惑,因为每次我的条件为真并且程序跳转到 if 树但那时 SD 卡上没有文件...

    String filename = "pictures.data";
    String root = Environment.getExternalStorageDirectory().toString();
    File dir = new File(root + "/courier/saved/");
    File file = new File(dir,filename);

    if (file.exists())
        // program jumps here
    else{

    }

【问题讨论】:

  • 为什么使用toString()方法?您可以使用返回字符串的File.getPath()
  • PRint 变量根。 getExternalStorageDirectory() 不能可靠地提供 sd 卡位置(我已经看到不同的设备为此表现不同)。一旦你确认根变量确实指向外部 SD 卡,那么你可以进一步挖掘
  • /storage/sdcard0 是我的外部存储,所以 /storage/sdcard0/courier/saved/ 被添加到路径中

标签: android file file-exists


【解决方案1】:

好的,这样您就可以在目录 /courier/saved/ 中看到该文件。无论如何,这是我的答案

String filename = "pictures.data";
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/courier/saved/");
File file = new File(dir,filename);
file.mkdirs();
if (file.exists())
    // program now stops here
else{

}

最好是事先创建目录,但这会动态创建它

【讨论】:

  • 在下一步我检查文件是否不存在然后我有条件 if (!dir.exists()) { dir.mkdirs();} 但如果文件存在然后从文件中读取然后保存它再次...
  • 顺便说一句,欢迎使用 Stackoverflow。这是一个新问题,您必须照原样发布。在创建新问题期间,您将看到许多现有答案,请尝试一下。然后按我的答案上的接受以关闭问题。如果您认为我的回答解决了这个问题,请按接受并投票,如果您满意
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多