Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java / JavaSE

Compressing and Uncompressing Files in Java

3.33/5 (6 votes)
7 Jan 2009CPOL 39.5K   2K  
In this article, I’ll show you how to compress and extract files easily in Java using ziputil.jar.

Introduction

In this article, I'll show you how to compress and extract files easily in Java using ziputil.jar.

Background

You don't need any external libraries or configurations except ziputil.jar to test this project. You can download the source from the link at the top of this article. Source code for the project contains source for ziputil.jar and test classes and files to be tested.

Compressing Files

Uncompressed file class represents an uncompressed state of a zip file. Before compressing a set of files, you need to create an Uncompressed file as shown below passing the path to create the new zip file.

Java
UncompressedFile u=new UncompressedFile("./testFiles/TEST.ZIP");        

Then you can add files which needed to be compressed, to UncompressedFile

Java
u.addFile(new BinaryFileData("test1.txt",
ZipFileUtil.fileToBytes("./testFiles/test1.txt")));

u.addFile(new BinaryFileData("test2.BUP",
ZipFileUtil.fileToBytes("./testFiles/test2.BUP")));

u.addFile(new BinaryFileData("test3.BUP",
ZipFileUtil.fileToBytes("./testFiles/test3.BUP")));

u.addFile(new BinaryFileData("test4.BUP",
ZipFileUtil.fileToBytes("./testFiles/test4.BUP")));        

Now you are ready to compress these files. Call the method ZipFileUtil.compress as shown below: 

Java
byte[] b=ZipFileUtil.compress(u);    

Finally call ZipFileUtil.byteArrayToFile to save the new zip file to your file system.  

Java
ZipFileUtil.byteArrayToFile(u.getPath(),b);     

Extracting Files

To uncompress a file, call the ZipFileUtil.extract method passing path to the zip file to be extracted and path of the folder to save extracted files as below: 

Java
UncompressedFile u=
ZipFileUtil.extract("./testFiles/TEST.ZIP","./testFiles/extract");
ZipFileUtil.saveUncompressedFile(u);        

History

  • 7th January, 2009: Article created (ziputil.zip is not explained yet)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)