Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/194.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取FileNotFoundException/EISDIR_Java_Android_File_Exception - Fatal编程技术网

Java 获取FileNotFoundException/EISDIR

Java 获取FileNotFoundException/EISDIR,java,android,file,exception,Java,Android,File,Exception,我得到这个错误 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.get

我得到这个错误

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();
}          
更新添加代码删除与所需文件名匹配的目录(f any)+正确使用mkdirs似乎解决了问题。已接受最接近的答案。

请注意

f.mkdirs();
您需要检查此语句的返回值。如果为true,则继续,否则路径不存在。

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

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

您是否声明了
WRITE\u EXTERNAL\u STORAGE
权限?路径是否包含文件名?@giorasch Yes itdoes@AndyRes是的,我有。(虽然我不确定写入应用程序自己的缓存文件夹时是否需要这样做。)@giorashc-ya-right。我只是给他指路,让他自己找到正确的答案。因此,我们不需要做填鸭式喂食我会添加代码来检查,但仅供参考,这是真的。我现在已经改为使用您的代码。但我还是犯了同样的错误。如果有一个目录与我正在创建的文件同名,我将尝试进行删除,如果是,可能会先尝试删除它。(用你的解决方案更加努力,这应该能解决问题)