Zip a Directory In Java

Through its 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(".\"));     //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 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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS