Through its java.util.zip package, Java provides you with an easy mechanism to compress/decompress files. Here is a method called zipDir, that shows how to recursively zip a directory structure.
Note that the following method does not add an empty directory to the produced ZIP file.
//the method accepts a String for the directory that should be zipped, and a ZipOutputStream to write the zipped data to.
So the code to invoke the method might be:
try { //create a ZipOutputStream to zip the data to ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(".\curDir.zip")); //assuming that there is a directory named inFolder (If there //isn't create one) in the same directory as the one the code runs from, //call the zipDir method zipDir(".\inFolder", zos); //close the stream zos.close(); } catch(Exception e) { //handle exception } //here is the code for the method public void zipDir(String dir2zip, ZipOutputStream zos) { try { //create a new File object based on the directory we have to zip File zipDir = new File(dir2zip); //get a listing of the directory content String[] dirList = zipDir.list(); byte[] readBuffer = new byte[2156]; int bytesIn = 0; //loop through dirList, and zip the files for(int i=0; i
Now, you should have a curDir.zip in the application's directory. If you view it with a ZIP utility, you'll see that it contains the contents of the directory inFolder.