We help IT Professionals succeed at work.

Zipping folders and sub folders in Java

pdurbha
pdurbha asked
on
Hi,
The attached code zips up all the files present in C:\abc\ss into C:\Abc.zip at the top level. When I open up the zip file using WinZip and extract the file into another folder temp, the subfolders "abc" and "ss" are lost. All the files are getting extracted to the top level only i.e. C:\temp. ( and not C:\temp\abc\ss).

How can I change this code to make sure that the sub folders also get zipped during the process?

Thanks
try
 {
	     File inFolder=new File("C:\\abc\\ss");
	     File outFolder=new File("C:\\Abc.zip");
	     ZipOutputStream out = new ZipOutputStream(new 
	BufferedOutputStream(new FileOutputStream(outFolder)));
	     BufferedInputStream in = null;
	     byte[] data    = new byte[1000];
	     String files[] = inFolder.list();
	     for (int i=0; i<files.length; i++)
	      {
	      in = new BufferedInputStream(new FileInputStream
	(inFolder.getPath() + "/" + files[i]), 1000);                  
	out.putNextEntry(new ZipEntry(files[i])); 
	      int count;
	      while((count = in.read(data,0,1000)) != -1)
	      {
	           out.write(data, 0, count);
	          }
	      out.closeEntry();
	      }
	      out.flush();
	      out.close();
	      }
	      catch(Exception e)
	         {
	              e.printStackTrace();
	          } 
	}

Open in new window

Comment
Watch Question

Commented:
To retain directory information for each zipped file, chage the name of the ZipEntry object to reflect the path...

Line 14: out.putNextEntry(inFolder.getPath() + "/" + new ZipEntry(files[i]));

Commented:
To add subdirectories and their contents, use recursion - something like the snippet. I haven't thought about whether File objects are the right way to go, etc. Just presenting a concept.

Somebody else tried the same thing you're doing:
http://panmental.de/public/programming_projects/HowTos/useCondorWithSubdirectories.php
File f = new File(fName);
if (f.isDirectory())
 doDirectory(f);
else
 addFile(f); // you already have this part
 
public static void doDirectory(File f) {
if (f.isDirectory())
 doDirectory(f);
else
 addFile(f); 
}

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.