File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes Problem in unzipping a folder using java.util.zip API Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Problem in unzipping a folder using java.util.zip API" Watch "Problem in unzipping a folder using java.util.zip API" New topic
Author

Problem in unzipping a folder using java.util.zip API

ram shyam
Ranch Hand

Joined: May 04, 2007
Posts: 77
Hi all,

I am using the following code to unzip a folder but eventually I find that few files are just created but has no content in them. I have no clue why few files are missed out in writing the content alone.



The folder structure after unzip will be -
Parent - containing 3 folders - each containinng multiple .txt files. In this few .txt files are empty (has no content inside). Please let me know what could be the problem in which only few files are missed out while unzipping.

Thanks in advance!!

[ UD: Please UseCodeTags when posting code of any length. It's unnecessarily hard to read without them, making it less likely that people will take the time to do so (and thus be able to answer your question). ]
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42929
    
  68
Are there any exceptions? Your exception handling doesn't notify you if there are any.
ram shyam
Ranch Hand

Joined: May 04, 2007
Posts: 77
Hi,

No, there are no exceptions caught as well. I have checked by uncommenting the printstacktrace code. The while loop of writitng to the fileoutputstream is called only once in those files and the content is empty. I have no clue why this happens to selective files.

Please let me know what would have gone wrong.

Thanks in advance!!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19785
    
  20

Quite unrelated, but you should consider caching results of method calls if you call them often. For instance, I've seen quite a few times in your code. You already have this value stored in "zipFileLocation", so why not use this variable some more. The same goes for some of the File objects.
It would also make your code a bit more readable since the lines will be a lot shorter.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42929
    
  68
It looks like you're not handling directories correctly. All the code involving "dest" should not be run for directories, because "fos" has no valid value in that case.
ram shyam
Ranch Hand

Joined: May 04, 2007
Posts: 77
Hi all,

I tried changing the writing FOS part of the code as follows but still the output is the same. Few .txt files are created but still there are no contents in them -

FileOutputStream fos = null;
if (!entry.isDirectory())
{
fos = new FileOutputStream(fileName.substring(0, fileName.length()-4) + "/" + entry.getName().substring(entry.getName().indexOf("/")));
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
}

Please let me know if there is any other means of doing unzip of a folder.zip. Since this code seems not to be working in all cases.

Thanks in advance!!
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42929
    
  68
The logic of the code is hard to follow, what with all the string operations. You may want to print out the entries the code encounters, under which path it's trying to save each one, and how many bytes it read and writes for each entry.

Be sure to properly handle exceptions; at the very least print them out so that you know if they're happening.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19785
    
  20

You should create the folder in the else block as well - if the zip entry is a directory entry, create its matching folder in the file system.
Or at least create the parent folder before trying to write to a file.
ram shyam
Ranch Hand

Joined: May 04, 2007
Posts: 77
Hi all,

To re-iterate the problem I am facing, following is the code I am using -

--------------------------------------------------------------------------------------------
final int BUFFER = 2048;
try {
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(fileName);
Enumeration e = zipfile.entries();

zipFileLocation = fileName.substring(0, fileName.length()-8);
new File(fileName.substring(0, fileName.length()-4)).mkdirs();

while(e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
System.out.println("Extracting: " +entry);
is = new BufferedInputStream
(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];

if (!(entry.getName().substring(entry.getName().indexOf("/"))).endsWith("txt")) // To check if its a .txt file or a directory
new File(zipFileLocation + entry.getName().substring(entry.getName().indexOf("/"))).mkdirs(); // create the unzipped directories
else
new File(zipFileLocation + entry.getName().substring(entry.getName().indexOf("/"))).createNewFile(); // create the .txt file under the unzipped directories
FileOutputStream fos = null;
if (!entry.isDirectory())
{
fos = new FileOutputStream(zipFileLocation + "/" + entry.getName().substring(entry.getName().indexOf("/")));
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
}
dest.flush();
dest.close();
is.close();
}
} catch(Exception e) {
e.printStackTrace();
}
-----------------------------------------------------------------------------------------------

The above code creates the unzipped directories and the .txt files correctly but only few .txt files are empty without any contents which I am still unable to resolve. Hence I tried using the Runtime library in which I am facing the problem in windows but not in solaris. Following is the code -


-----------------------------------------------------------------------------------------------------

Runtime runTime = Runtime.getRuntime();
Process process = null;
String[] command = {"unzip " + fileName};
System.out.println("command " + command);
try
{
process = runTime.exec(command);
InputStream ins = process.getErrorStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(ins));
System.out.println(bfr.readLine());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}

----------------------------------------------------------------------------------

When the filename is C:\Documents and Settings\egrdeep\My Documents\maud.zip, I get the following error as -
unzip: cannot find either C:/Documents or C:/Documents.zip. Looks like the space is the problem while running in windows. Please let me know a solution to either the java.util.zip problem or the Runtime unzip problem.

Thanks in advance!!
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42929
    
  68
String[] command = {"unzip " + fileName};

This is a problem. You shouldn't concatenate the executable name and its arguments into a single string. Use something like
String[] command = {"unzip", fileName};
ram shyam
Ranch Hand

Joined: May 04, 2007
Posts: 77
Hi,

Thanks for your reply!

Now, I am not getting that error but looks like unzip is not working. I tried to print the errorStream to check if there is any error occured during unzip, but bfr.readLine() hangs. If I remove the errorStream code, no exception is caught, the code runs fine but no unzip occurs. I could not find any unzipped folder created in windows.

------------------------------------------------
String[] command = {"unzip" ,fileName};
System.out.println("command " + command[0] + command[1]);
try
{
process = runTime.exec(command);
InputStream ins = process.getErrorStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(ins));
String line = null;
while((line = bfr.readLine()) != null) {
System.out.println(line);
}


}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
---------------------------------------------------------------------------------

Please help me in solving this issue.

Thanks in advance!!
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42929
    
  68
The proper handling of the streams is described in this article.
ram shyam
Ranch Hand

Joined: May 04, 2007
Posts: 77
Hi,

Thanks for your reply!

I looked into the artilce and the unzip works fine now but unzips the zip file in the current location of where the code is running. But, I wanted the unzip to happen in the same location as that of .zip file is present. So, I used the command as - "unzip <filename> -d <target> which throws "parameter incorrect error".

Following is the code -
---------------------------------------------------------------------------------
zipFileLocation = fileName.substring(0, fileName.length()-4);
try
{
String osName = System.getProperty("os.name" );
String[] cmd = new String[6];
if( osName.equals( "Windows NT" ) )
{
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = "unzip";
cmd[3] = fileName;
cmd[4] = "-d";
cmd[5] = zipFileLocation;
}
else if( osName.equals( "Windows 2000" ) )
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = "unzip";
cmd[3] = fileName;
cmd[4] = "-d";
cmd[5] = zipFileLocation;
}

Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2] + " " + cmd[3] + " " + cmd[4] + " " + cmd[5]);

process = runTime.exec(cmd);
InputStream ins = process.getErrorStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(ins));
String line = null;
while((line = bfr.readLine()) != null) {
System.out.println(line);
}




}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}

------------------------------------------------------------------------

Follwing is the error -
Cannot run program "command.com": CreateProcess error=87, The parameter is incorrect

Please let me know how to resolve this.

Thanks in advance!!
ram shyam
Ranch Hand

Joined: May 04, 2007
Posts: 77
Hi,

Currently I have one more issue to be solved. When I run the following code from eclipse IDE, the code runs fine. But when I create a jar file with the class files and run that jar file from command line, I get the following error - C:\WINNT\system32\ntvdm.exe Erro while setting up environment for the application. Choose 'Close' to terminate the application

-------------------------------------------------------------------------------------------------------------

try
{
String osName = System.getProperty("os.name" );
String[] cmd = new String[4];
if( osName.startsWith("Win"))
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = "unzip";
cmd[3] = fileName;
}

Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2] + " " + cmd[3]);

process = runTime.exec(cmd);
InputStream ins = process.getErrorStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(ins));
String line = null;
while((line = bfr.readLine()) != null) {
System.out.println(line);
}
int exitval = process.waitFor();
System.out.println("Wait over..." + exitval);



}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
-----------------------------------------------------------------------------------------------------------------------

Please let me know how to solve this issue.
Thanks in advance!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem in unzipping a folder using java.util.zip API