java 尝试写入文件时出现 FileNotFound 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2541425/
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-10-29 21:41:24  来源:igfitidea点击:

FileNotFound exception when trying to write to a file

javafileexceptionfilenotfoundexception

提问by Chris Knight

OK, I'm feeling like this should be easy but am obviously missing something fundamental to file writing in Java. I have this:

好的,我觉得这应该很容易,但显然我缺少用 Java 编写文件的一些基本知识。我有这个:

File someFile = new File("someDirA/someDirB/someDirC/filename.txt");

and I just want to write to the file. However, while someDirA exists, someDirB (and therefore someDirC and filename.txt) do not exist. Doing this:

我只想写入文件。然而,虽然 someDirA 存在,但 someDirB(因此 someDirC 和 filename.txt)不存在。这样做:

BufferedWriter writer = new BufferedWriter(new FileWriter(someFile));

throws a FileNotFoundException. Well, er, no kidding. I'm trying to create it after all. Do I need to break up the file path into components, create the directories and then create the file before instantiating the FileWriter object?

抛出一个FileNotFoundException. 嗯,呃,不开玩笑。毕竟,我正在尝试创建它。在实例化 FileWriter 对象之前,我是否需要将文件路径分解为组件、创建目录然后创建文件?

回答by

You have to create all the preceding directories first. And hereis how to do it. You need to create a Fileobject representing the path you want to exist and then call .mkdirs()on it. Then make sure you createthe new file.

您必须首先创建所有上述目录。而这里是如何做到这一点。您需要创建一个代表您想要存在的路径的File对象,然后在其上调用.mkdirs()。然后确保您创建了新文件。

final File parent = new File("someDirA/someDirB/someDirC/");
if (!parent.mkdirs())
{
   System.err.println("Could not create parent directories ");
}
final File someFile = new File(parent, "filename.txt");
someFile.createNewFile();

回答by Andy White

You can use the "mkdirs" method on the File class in Java. mkdirs will create your directory, and will create any non-existent parent directories if necessary.

您可以在 Java 中的 File 类上使用“mkdirs”方法。mkdirs 将创建您的目录,并在必要时创建任何不存在的父目录。

http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdirs%28%29

http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdirs%28%29