Rathakrishnan Ramasamy
Rathakrishnan Ramasamy

Reputation: 1612

Create Directory along with file using file stream in java

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.

Upvotes: 1

Views: 890

Answers (2)

Adam
Adam

Reputation: 36703

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();
}

Upvotes: 4

Java42
Java42

Reputation: 7706

Here you go...

boolean b = (new File("D:/Data/files/store/file.txt").getParentFile()).mkdirs();

Upvotes: 2

Related Questions