FileNotFound exception when trying to write to a file
Asked Answered
C

2

11

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?

Concertino answered 29/3, 2010 at 21:30 Comment(0)
L
21

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

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();
Lara answered 29/3, 2010 at 21:33 Comment(3)
Thanks, but there are a few non-factual bits above. Firstly, you can call mkdirs() on existing directories and it will simply return false rather than throw an exception. Also, in my case, once the directories are created, I can skip the createNewFile() step and go straight to the FileWriter step.Concertino
createNewFile() is redundant hence downvoting.Aaronaaronic
createNewFile() is retundant but rest of the code works fine. Hence upvoting.Manas
M
2

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.

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

Mckoy answered 29/3, 2010 at 21:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.