0

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.

1
  • In Java API you have File.mkdirs() which will help you. Which will create all necessary directories. Commented Apr 11, 2013 at 7:08

4 Answers 4

3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

That makes a nice change ;)
1

Something like this must work:

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

1 Comment

Don't need the "//", single "/" are fine ... +1 otherwise
0

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

}

5 Comments

What happens if the mkdirs call fails? Do you have to do another fileDir.exists() to check for it? Seems like a waste of effort to me. Right idea though
What do you mean if it fails? I don't get you.
mkdirs can fail - From the docs "Note that if this operation fails it may have succeeded in creating some of the necessary parent directories"
Oh. I used this code, so I copied here and it was working fine for me. So what is the best option to create directory then?
The code is fine, but now you need to do another check to see if it worked. Try using something more like if (fileDir.exists() || fileDir.mkdirs()) {...} assuming that fileDir is the path you want to create..
0

Here's what you need to do first:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.