FileNotFound exception when trying to write to a file

Chris Knight picture Chris Knight · Mar 29, 2010 · Viewed 11.7k times · Source

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?

Answer

user177800 picture user177800 · Mar 29, 2010

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();