Zip Your File In Java

Today, I will show you how to create a program that will zip your file using Java.

So, now let’s start this tutorial!

1. Open Notepad. Encode any data in there and save it to the same folder with your java program and named it as READ FIRST.txt (Note: you can name your text file in any name that you want).

2. Open JCreator or NetBeans and make a java program with a file name of

3. Import package. We will use an input/output in creating files. Import also package to access the zip class from this utilities.


4. In your main, initialize the data.txt that you have created a while ago for this file. This READ FIRTS.txt file is the file that we will going to locate. Initialize the name of the zip file after compression. Here we will be using This will be in your Try and Catch method.

try {
String file = "READ FIRST.txt";
String zipFile = "";

Make a ZipOutputStream for the zipFile variable that you have created. This will trigger to have an output for zipping. Then the FileInputStream for file variable that will be your input file.

ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
FileInputStream fileStream = new FileInputStream(file);

Now, put a new ZipEntry in the ZipOutputStream.

zipStream.putNextEntry(new ZipEntry(file));

Initialize the value of the file size and its byte.

int size = 0;
byte[] buffer = new byte[1024];

Create a while loop that reads data to the end of the file and write it to the zip for the outputstream.

while ((size =, 0, buffer.length)) > 0) {
zipStream.write(buffer, 0, size);

Close the zip process after finishing the compression.


In your Catch method, prefer to catch IOException then use printStackTrace() method. This will help you to trace the exception and identify which method causes the bug.

catch (IOException e) {



Download Code

Sharing is caring!

Facebook Comments

Leave a Reply