Felix
Felix

Reputation: 1263

Create a java file with directory

I am trying to create a file (/data/test/userid/feedid/test.flv)

If that directory does not exist, I get this exception:

java.io.FileNotFoundException

Is there any good way to solve this problem?

I have found commons.io, but there isn't any function that can solve this.

Upvotes: 0

Views: 182

Answers (4)

MadProgrammer
MadProgrammer

Reputation: 347184

File#mkdirs will create the paths structure denoted by this File. For example

File file = new File("/data/test/userid/feedid/test.flv");
File parent = file.getParentFile();
if (parent.exists() || parent.mkdirs()) {
   //...
} else {
    throw new IOException("Failed to create output directory " + parent);
}

Upvotes: 3

Emon
Emon

Reputation: 9

Here's what you need to do first:

File dir = new File("/data/test/userid/feedid");
if (!dir.exists()){ 
     dir.mkdir();
}

Upvotes: 0

Gokul Nath KP
Gokul Nath KP

Reputation: 15553

Something like this must work:

File file = new File("data//test//userid//feedid//test.flv");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

Upvotes: 1

iCode
iCode

Reputation: 9202

Try this

String fileLocation= //your location to store;
File fileDir=new File(fileLocation);
if(!fileDir.exists())
{
    fileDir.getParentFile().mkdirs(); // to create directory if not exists

}

Upvotes: 0

Related Questions