I have a String like this "D:/Data/files/store/file.txt"
now I want to check ,is directory is already exist or not, if not I want to create directory along with text file. I have tried mkdirs()
but its creating directory like this data->files->store->file.txt
. means its creates file.txt
as folder, not a file. can any one kindly help me to do this. thanks in advance.
Asked
Active
Viewed 860 times
1

Rathakrishnan Ramasamy
- 1,612
- 2
- 25
- 46
-
take a look at http://docs.oracle.com/javase/7/docs/api/java/io/File.html you'll find all the methods you need. – ma cılay Mar 13 '12 at 00:39
-
possible duplicate of [Create whole path automatically when writing to a new file](http://stackoverflow.com/questions/2833853/create-whole-path-automatically-when-writing-to-a-new-file) – ring bearer Mar 13 '12 at 00:43
2 Answers
4
You need to run mkdirs() on parent directory, not the file itself
File file = new File("D:/Data/files/store/file.txt");
file.getParentFile().mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

Adam
- 35,919
- 9
- 100
- 137
2
Here you go...
boolean b = (new File("D:/Data/files/store/file.txt").getParentFile()).mkdirs();

Java42
- 7,628
- 1
- 32
- 50