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);
Mercer
  • 9,736
  • 30
  • 105
  • 170

2 Answers2

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);
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 1
    would it be worth it to add a `&& !parent_directory.exists()` to the `if` check? – Matt Felzani Aug 10 '12 at 05:44
  • 4
    @MattFelzani, you could but `mkdirs()` only returns `true` it if it created the directory, which implies it performs an existence check itself. – hmjd Aug 10 '12 at 07:37
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

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
Mechkov
  • 4,294
  • 1
  • 17
  • 25