gpt4 book ai didi

java - 获取 FileNotFoundException/EISDIR

转载 作者:太空宇宙 更新时间:2023-11-03 11:50:36 26 4
gpt4 key购买 nike

我收到这个错误

java.io.FileNotFoundException: /data/data/com.example.app/cache/news.xml: open failed: EISDIR (Is a directory)

使用这段代码

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 似乎已经解决了问题。接受最接近的答案。

最佳答案

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

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

关于java - 获取 FileNotFoundException/EISDIR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17548812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com