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.
Asked
Active
Viewed 323 times
0

Mr.
- 9,429
- 13
- 58
- 82
-
1Perfect, now we know what you like to do... what have you tried so far? – home Jul 08 '12 at 07:44
-
Duplicate:http://stackoverflow.com/questions/6142901/how-to-create-a-file-in-a-directory-in-java – Cratylus Jul 08 '12 at 07:46
2 Answers
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
-
Please correct to `myFile.getParentFile().mkdirs()` so I could mark your post as an answer; and... thank you. – Mr. Jul 08 '12 at 07:50
-
@MrRoth I think it was long corrected before you post your comment. – Boris Strandjev Jul 08 '12 at 07:55
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