Zip Your File In Java | Free Source Code

Zip your File in Java

zip

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 zipFile.java.

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

import java.io.*;
import java.util.zip.*;

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 createdZipFile.zip. This will be in your Try and Catch method.

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

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 = fileStream.read(buffer, 0, buffer.length)) > 0) {
zipStream.write(buffer, 0, size);
}

Close the zip process after finishing the compression.

zipStream.closeEntry();
fileStream.close();
zipStream.close();

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) {
e.printStackTrace();
}


Output:

output

Download Code
Facebook Comments

Leave a Reply

Your email address will not be published.