java - file.createNewFile() IOException“没有这样的文件或目录”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26239151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:32:59  来源:igfitidea点击:

java - file.createNewFile() IOException "No such file or directory"

javaioexception

提问by Mugi4ok

While coding Java had this problem: file.createNewFile() throws IOException "No such file or directory". Checked out other answers but nothing seems to be helpful. Any ideas?..

在编码 Java 时有这个问题:file.createNewFile() 抛出 IOException “没有这样的文件或目录”。查看了其他答案,但似乎没有任何帮助。有任何想法吗?..

采纳答案by Mugi4ok

Oh, I got it. It appeared to be more Windows problem than Java. Actually, even with UAC disabled random app still have no rights to write something on C: (or whatever it is on your system) on Win8. Never got this problem using Win7 though. Using "Run as Administrator" on IDE does not help as it doesn't give such rights to Java compiler. So, I just moved my projects folder to other disk. Also, you can change access rights, but it was easier for me. And yes, nobody mentioned about a chance of this happening in other questions, so I hope it'll be helpful to anyone.

哦,我明白了。它似乎比 Java 更像是 Windows 问题。实际上,即使禁用了 UAC,随机应用程序仍然无权在 Win8 上的 C:(或您系统上的任何内容)上写一些东西。不过使用Win7从来没有遇到过这个问题。在 IDE 上使用“以管理员身份运行”无济于事,因为它没有授予 Java 编译器这样的权限。所以,我只是将我的项目文件夹移动到其他磁盘。此外,您可以更改访问权限,但这对我来说更容易。是的,没有人提到在其他问题中发生这种情况的可能性,所以我希望它对任何人都有帮助。

回答by kapex

It could be that you are trying to create the file in a directory that does not exist.

可能是您试图在不存在的目录中创建文件。

Use mkdirs()to create any missing parent directories first.

用于mkdirs()首先创建任何缺少的父目录。

File file = new File("foo/bar.txt")
file.getParentFile().mkdirs();
file.createNewFile();

回答by Juru

I think you are trying to create a new file in a directory that does not exist. The whole path needs to exist, only the file can be non-existent.

我认为您正试图在不存在的目录中创建一个新文件。整个路径需要存在,只有文件可以不存在。

回答by dube

You need to create the Folder first. createNewFile cannot create them:

您需要先创建文件夹。createNewFile 无法创建它们:

File folderFile = new File("c:\this\folder\has\subfolders");
folderFile.mkdirs();

File myFile = new File(folderFile,"myfile.txt");
myFile.createNewFile();