directories in a zip file when using java.util.zip.ZipOutputStream

Lets say I have a file t.txt, a directory t and another file t/t2.txt. If I use the linux zip utility "zip -r t.zip t.txt t", I get a zip file with the following entries in them (unzip -l t.zip):

Archive: t.zip Length Date Time Name -------- ---- ---- ---- 9 04-11-09 09:11 t.txt 0 04-11-09 09:12 t/ 15 04-11-09 09:12 t/t2.txt -------- ------- 24 3 files

If I try to replicate that behavior with java.util.zip.ZipOutputStream and create a zip entry for the directory, java throws an exception. It can handle only files. I can create a t/t2.txt entry in the zip file and add use the t2.txt file contents to it but I can't create the directory. Why is that?

-------------Problems Reply------------

It looks like ZipOutputStream can't handle empty directories, but you have a file in there so its not empty. Try (from)

public class Test {
public static void main(String[] args) {
try {
FileOutputStream f = new FileOutputStream("test.zip");
ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f));
zip.putNextEntry(new ZipEntry("xml/"));
zip.putNextEntry(new ZipEntry("xml/xml"));
zip.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}

Java Program to Zip(folders contains either empty or full ones)

public class ZipUsingJavaUtil {
/*
* Zip function zip all files and folders
*/
@Override
@SuppressWarnings("finally")
public boolean zipFiles(String srcFolder, String destZipFile) {
boolean result = false;
try {
System.out.println("Program Start zipping the given files");
/*
* send to the zip procedure
*/
zipFolder(srcFolder, destZipFile);
result = true;
System.out.println("Given files are successfully zipped");
} catch (Exception e) {
System.out.println("Some Errors happned during the zip process");
} finally {
return result;
}
}

/*
* zip the folders
*/
private void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
/*
* create the output stream to zip file result
*/
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
/*
* add the folder to the zip
*/
addFolderToZip("", srcFolder, zip);
/*
* close the zip objects
*/
zip.flush();
zip.close();
}

/*
* recursively add files to the zip files
*/
private void addFileToZip(String path, String srcFile, ZipOutputStream zip, boolean flag) throws Exception {
/*
* create the file object for inputs
*/
File folder = new File(srcFile);

/*
* if the folder is empty add empty folder to the Zip file
*/
if (flag == true) {
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName() + "/"));
} else { /*
* if the current name is directory, recursively traverse it
* to get the files
*/
if (folder.isDirectory()) {
/*
* if folder is not empty
*/
addFolderToZip(path, srcFile, zip);
} else {
/*
* write the file to the output
*/
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
/*
* Write the Result
*/
zip.write(buf, 0, len);
}
}
}
}

/*
* add folder to the zip file
*/
private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception {
File folder = new File(srcFolder);

/*
* check the empty folder
*/
if (folder.list().length == 0) {
System.out.println(folder.getName());
addFileToZip(path, srcFolder, zip, true);
} else {
/*
* list the files in the folder
*/
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false);
}
}
}
}
}

Just go through the source of java.util.zip.ZipEntry. It treats a ZipEntry as directory if its name ends with "/" characters. Just suffix the directory name with "/".

Check this example for zipping just the empty directories, http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_ZipUtilities_ZipEmptyDirectory

Good luck.

You can at "/" at the end of folder name. Just use follow command zip.putNextEntry(new ZipEntry("xml/"));

Like others said here to add empty directory add "/" to the directory name. Pay attention NOT to add File.separator (equals to "\") which actually add an empty file to the zip.

It took me a while to understand what was my mistake - hope I save other some time...

Category:java Views:5 Time:2009-04-11

Related post

  • java.util.zip.ZipException: Central Directory Entry not found 2011-04-12

    I have a code which runs absolutely fine on emulator but when I run it on Samsung Galaxy Tab, it gives Exception. I am receiving one compressed zip file from server via socket and than I am extracting these file. If I compress and send two or three t

  • Why I get an Exception on opening an empty ZIP-file with java.util.zip.ZipFile? 2008-12-12

    I want to open a ZIP-file, that have no entries with java.util.zip.ZipFile. But on the constructor I get the following exception: 'java.util.zip.ZipException: error in opening zip file'. How can I open the empty ZIP? That ZIP-file is created by the c

  • java.util.zip.ZipException: too many entries in ZIP file 2009-01-27

    I am trying to write a Java class to extract a large zip file containing ~74000 XML files. I get the following exception when attempting to unzip it utilizing the java zip library: java.util.zip.ZipException: too many entries in ZIP file Unfortunatel

  • JBoss deployment throws 'java.util.zip.ZipException: error in opening zip file' on Linux? 2010-04-10

    I deployed a large EAR (contained more than ~1024 jars/wars) on JBoss running with Java 6 on Linux, and the deployment process cried throwing the following exception: java.lang.RuntimeException: java.util.zip.ZipException: error in opening zip file)

  • How to estimate zip file size in java before creating it 2010-08-26

    I am having a requirement wherein i have to create a zip file from a list of available files. The files are of different types like txt,pdf,xml etc.I am using java util classes to do it. The requirement here is to maintain a maximum file size of 5 mb

  • java.util.zip.ZipException: error in opening zip file 2010-09-10

    i am geting this strange exception below: INFO: Deploying web application archive ZangV3Spring.war 10-Sep-2010 08:46:38 org.apache.catalina.startup.ContextConfig init SEVERE: Exception fixing docBase for context [/ZangV3Spring] java.util.zip.ZipExcep

  • Error opening zip file created using java 2010-11-01

    I created a small application to read some files from the disk and zip it using java.util.zip.ZipOutputStream. It is successfully creating the zip file. But in windows when i try to open it / extract it am getting the error message like "Windows has

  • Unzipping files in a faster way than using the java.util.zip in Android 2011-02-16

    I need unzip a .zip file of 2.5mb(1087 files - *.html, *.css and *.db) in android, i have used java.util.zip, it works fine, but i need improve the performance, the unzip process last 1.10 minutes, i need reduce this time. I have followed some recome

  • Any recommendation for zip file upload by java servlet? 2012-03-06

    I need to upload zip file to server by servlet? anyone can recommend me one? which can upload the zip file and then unzip the zip file. it will be good if it support upload several files together. thanks! --------------Solutions------------- use apac

  • java.util.zip - Recreating directory structure 2009-09-09

    While trying to zip an archive using the java.util.zip I ran into a lot of problems most of which I solved. Now that I finally get some output I struggle with getting the "right" output. I have an extracted ODT file (directory would be more fitting a

  • java.util.zip has problems with periods in filenames / directorynames? 2011-01-29

    I want to unzip an iPhone app .ipa file. This is actually zip file that extracts normally. But the actual app file in it is a folder with the ending .app ( as all mac applications are actually folders with the ending .app). Now the period seems to be

  • What versions/flavors of WinZip can be opened by the gnu.java.util.zip.dll v.6.0.140.8? 2009-08-20

    Evaluating a third party data processing tool, I have bumped into a case where some WinZip files cause an exception: Caused by: gnu.java.util.zip.ZipException: Unknown compression method 98 at gnu.java.util.zip.ZipFile.getInputStream(ZipFile.java:470

  • Problem when compressing SWF in Linux with java.util.zip 2010-05-03

    I've created a servlet that changes the binaries of a SWF file and output it to the user. The SWF is compressed by ZLIB by default. Then I inflate, change the binaries, deflate and output the result. Everything was running right on a Windows Server 2

  • java.util.zip.ZipException: oversubscribed dynamic bit lengths tree 2010-06-15

    I am compressing a string using gzip, then uncompress the result, however I got the following exception, why? output: Exception in thread "main" java.util.zip.ZipException: oversubscribed dynamic bit lengths tree at java.util.zip.InflaterInputStream.

  • What is the Python equivalent of java.util.zip.Inflater? 2010-06-23

    I have a Java program that opens a socket connection to a server that streams Zip compressed data. I read(bytebuffer) from the stream, setInput(bytebuffer) on the zip object, and inflate(outputbuffer) to get my uncompressed data. What would be the eq

  • java.util.zip.ZipException: incomplete literal/length tree 2010-07-06

    I have this problem when I try to deploy my webapp(name:auditadmin.war) on tomcat 5.05. I did the following:auditadmin.war was already deployed & working fine.Then I edited one jsp page rebuilt it using ant & deployed the new war file.Till th

  • java.util.zip.zipexception : unknown compression method 2010-07-18

    I am working with a third party API http://jortho.sourceforge.net/ While using the API, I always get an exception java.util.zip.zipexception : unknown compression method There are no zip files involved, I tried not using the .jar file of the API, ins

  • imports java.util.zip in a vb.net project 2010-08-31

    I need to import java.util.zip for my project to zip and unzip chosen files/folders in vb.net. But when i say imports java.util.zip, i get the error "Namespace cannot be found". I went in the add reference and checked in both .net and COM components

  • Why are my java.util.zip functions showing inconsistent behavior? 2011-01-28

    I have a Java application that uses the java.util.zip library to compress and decompress files. What I have is a zip file on the server (created by my application) and the client zipping some of his files and uploading the file to the server, but if

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.180 (s). 11 q(s)