Directory does not exist with FileWriter

Mercer picture Mercer · Dec 29, 2011 · Viewed 9.4k times · Source

I use FileWriter for create a file. I have an error Directory does not exist I think that FileWriter create the directory if it did not exist

FileWriter writer = new FileWriter(sFileName);

Answer

hmjd picture hmjd · Dec 29, 2011

java.io.FileWriter does not create missing directories in the file path.

To create the directories you could do the following:

final File file = new File(sFileName);
final File parent_directory = file.getParentFile();

if (null != parent_directory)
{
    parent_directory.mkdirs();
}

FileWriter writer = new FileWriter(file);