tags:

views:

40

answers:

2

Hai friends,

Am downloading a ZipFile from web. where it contain folders and files. Uncompressing them using zipInputstream and zipentry . zipentry.getName giving name of file as "htm/css/aaa.htm".

so i am creating New File(zipentry.getName);

But problem it throwing an exception File not found. i got that it is creating subfolders htm and css. My question is that , how to create a file including its sub directories , by passing above path ?

Can anyone sort out this problem , please am thankful to you .

Thanking you, Sai Srinivas

+2  A: 

Use this:

File targetFile = new File("foo/bar/phleem.css");
File parent = targetFile.getParentFile();
if(!parent.exists() && !parent.mkdirs()){
    throw new IllegalStateException("Couldn't create dir: " + parent);
}

While you can just do file.getParentFile().mkdirs() without checking the result, it's considered a best practice to check for the return value of the operation. Hence the check for an existing directory first and then the check for successful creation (if it didn't exist yet).

Reference:

seanizer
Thank you , i got it. it solve s ony one parent right.
Srinivas
if i have a/b/c/d/e.txt. to create e.txt. i have to create a , b, , c,d folders. how can i get it ?
Srinivas
mkDir() only creates one level of parents, mkDirs() creates all parents, grandparents etc.
seanizer
as I wrote: new File("a/b/c/d/e.txt").getParentFile().mkDirs() creates all needed folders, not just the parent folder
seanizer
It should be `mkdirs` not `mkDirs`. Small 'd'.
dogbane
changed that. so used to using autocompletion.
seanizer
great reason for a downvote btw. who knows, maybe I also forgot a semicolon somewhere.
seanizer
Thank you very much. it solved now.
Srinivas
then maybe you should accept an answer (click the checkmark next to it)
seanizer
+2  A: 

You need to create subdirectories if necessary, as you loop through the entries in the zip file.

ZipFile zipFile = new ZipFile(myZipFile);
Enumeration e = zipFile.entries();
while(e.hasMoreElements()){
    ZipEntry entry = (ZipEntry)e.nextElement();
    File destinationFilePath = new File(entry.getName());
    destinationFilePath.getParentFile().mkdirs();
    if(!entry.isDirectory()){
        //code to uncompress the file 
    }
}
dogbane
Looks good, but I'd do the folder creation inside the `if(!entry.isDirectory())` block, because you're creating all required parent folders anyway, so there's no need to do it when entry is a directory.
seanizer
Thanks dogbane..........
Srinivas