10

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

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:

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?

4

2 回答 2

20

您必须首先创建所有前面的目录。这是如何做到的您需要创建一个代表您想要存在的路径的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();
于 2010-03-29T21:33:02.333 回答
2

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

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

于 2010-03-29T21:35:10.603 回答