Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory does not exist with FileWriter

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);
like image 310
Mercer Avatar asked Dec 29 '11 14:12

Mercer


People also ask

Does FileWriter create the file if it does not exist?

FileWriter(String fileName) : Creates a FileWriter object using specified fileName. It throws an IOException if the named file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.

Does FileWriter overwrite existing file?

When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file.

Does FileWriter need to be closed?

It is not necessary to close it, because BufferedWriter takes care of closing the writer it wraps.


1 Answers

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);
like image 183
hmjd Avatar answered Sep 19 '22 11:09

hmjd