0

Assume final String fname = "/dir1/dir2/fname.ext". I do not wish to parse the string recursively in order to create the directories if they do not exist, and only then write to a file. I wish to use the given string, fname, for creating the directories and file if each of which does not exist.

Mr.
  • 9,429
  • 13
  • 58
  • 82

2 Answers2

2

This is the code you are looking for:

File myFile = new File("/dir1/dir2/fname.ext");
myFile.getParentFile().mkdirs();
// do your writing being sure the parent directories exist.
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
1

You can use mkdirs to create the path.

File f = new File("/dir1/dir2/fname.ext");
f.getParentFile().mkdirs();

And then work on the file itself.

Mendhak
  • 8,194
  • 5
  • 47
  • 64