Directory does not exist with FileWriter
Asked Answered
R

2

6

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);
Redbird answered 29/12, 2011 at 14:13 Comment(1)
well, apparently it doesn't!Eisenstein
P
19

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);
Partlow answered 29/12, 2011 at 14:22 Comment(2)
would it be worth it to add a && !parent_directory.exists() to the if check?Grandparent
@MattFelzani, you could but mkdirs() only returns true it if it created the directory, which implies it performs an existence check itself.Partlow
E
2

From the API documentation, we can conclude that FileWriter does not create a DIR if it does not exist:

FileWriter

public FileWriter(String fileName)
      throws IOException

Constructs a FileWriter object given a file name.

Parameters:
fileName - String The system-dependent filename.

Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

Ezmeralda answered 29/12, 2011 at 14:19 Comment(1)
Yes sir. It is a feasible way of doing it. Regards!Ezmeralda

© 2022 - 2024 — McMap. All rights reserved.