【问题标题】:Getting FileNotFoundException / EISDIR获取 FileNotFoundException / EISDIR
【发布时间】:2013-07-07 02:15:49
【问题描述】:

我收到此错误

java.io.FileNotFoundException: /data/data/com.example.app/cache/news.xml:打开失败: EISDIR(是一个目录)

使用此代码

try {
  File cache = ctx.getCacheDir();
  String s = cache.getAbsolutePath() + File.separator + path;
  File f = new File(s);
  File pf = f.getParentFile();
  if (pf != null) {
    pf.mkdirs();
  } 
  if ( (pf.exists()) && (pf.isDirectory()) ) {           
    if ( (!f.exists()) || (!f.isFile()) ) {
      f.createNewFile();
    }
    if ( (f.exists()) || (f.isFile()) ) {
      FileOutputStream os = null;        
      os = new FileOutputStream(s, false);            
      if (os != null) {
        SharedCode.sharedWriteTextFileToStream(str, os);                
      }
      os.flush();
      os.close();
    }
  }  
}  
catch (IOException e) {
  String s = e.toString();
}          

更新添加代码以删除与所需文件名匹配的目录(如果有的话)+ mkdirs 的正确使用似乎已经解决了问题。接受最接近的答案。

【问题讨论】:

  • 您是否声明了WRITE_EXTERNAL_STORAGE 权限?
  • 路径是否包含文件名?
  • @giorasch 是的
  • @AndyRes 是的,我有。 (虽然我不确定是否需要写入应用程序自己的缓存文件夹。)

标签: java android file exception


【解决方案1】:

mkdirs() 不仅会创建指向文件的目录,还会创建包含文件指向的路径的目录。这就是createNewFile() 失败的原因。您需要在父文件上调用mkdirs()

File parent = f.getParentFile();
if (parent != null) parent.mkdirs();

【讨论】:

  • 我现在改用你的代码了。但我仍然得到同样的错误。如果有一个与我正在创建的文件同名的目录,我将尝试检查是否存在,如果是这样,可能会先尝试将其删除。 (与您的解决方案一起,应该可以解决问题)
【解决方案2】:

请注意

f.mkdirs();

你需要检查这个语句的返回值。如果为真则继续,否则路径不存在。

【讨论】:

  • @giorashc 对。我只是给他指路,这样他就可以自己找到正确的答案。这样我们就不需要用勺子喂了
  • 我会添加代码来检查,但仅供参考,确实如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多