0% found this document useful (0 votes)
7 views16 pages

How To Compress Zip Files in Java

The document provides a comprehensive guide on how to compress files into ZIP format using Java, including multiple code examples for both password-protected and unprotected ZIP files. It covers the use of Java's built-in libraries as well as the external library 'zip4j' for more advanced features. Additionally, it explains how to handle files and directories, demonstrating the process of zipping and unzipping files with practical code snippets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views16 pages

How To Compress Zip Files in Java

The document provides a comprehensive guide on how to compress files into ZIP format using Java, including multiple code examples for both password-protected and unprotected ZIP files. It covers the use of Java's built-in libraries as well as the external library 'zip4j' for more advanced features. Additionally, it explains how to handle files and directories, demonstrating the process of zipping and unzipping files with practical code snippets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

How to Compress Zip Files in Java

En el capitulo de hoy vamos a ver como comprimir archivos en formato ZIP. Si bien a
Sometimes we have files that cannot be compressed too much; it's always very useful to zip them.
files by grouping them into a large file.

The code for the compression.

String inputFile = "c:/myfile.txt";


FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream("c:/myzip.zip");

byte b[] = new byte[2048];


ZipOutputStream zipOut = new ZipOutputStream(out);
ZipEntry entry = new ZipEntry(inputFile);
zipOut.putNextEntry(entry);
int len = 0;
while ((len = in.read(b)) != -1) {
zipOut.write(b, 0, len);
}
zipOut.closeEntry();
zipOut.close();

Another code for the same thing

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

/**
*
* @author GeekZero
*/
public class Files {

private static final int BUFFER_SIZE= 1024

public void Zippear(StringpFile,String pZipFile) throws


Exception {
objects in memory
FileInputStreamfis = null;
FileOutputStream fos = null;
ZipOutputStream zipos = null;

// buffer
byte[] buffer= new byte[BUFFER_SIZE];
try {
// file to compress
fis= new FileInputStream(pFile);
// container file of the zip
fos= new FileOutputStream(pZipFile);
compressed file
zipos= new ZipOutputStream(fos);
ZipEntry zipEntry = new ZipEntry(pFile);
zipos.putNextEntry(zipEntry);
int len= 0;
zippear
while (len= fis.read(buffer,0, BUFFER_SIZE))
!= -1)
zipos.write(buffer, 0, len);
dump the memory to disk
zipos.flush();
} catch (Exceptione) {
throw e;
} finally {
we close the files
zipos.close();
fis.close();
fos.close();
} // end try
} // end Zippear

public void UnZip(StringpZipFile,StringpFile) throws


Exception {
BufferedOutputStreambos = null;
FileInputStreamfis = null;
ZipInputStream zipis = null;
FileOutputStreamfos = null;

try {
fis= new FileInputStream(pZipFile);
zipis= new ZipInputStream(new
BufferedInputStream(fis));
if (zipis.getNextEntry() != null) {
int len= 0;
byte[] buffer= new byte[BUFFER_SIZE];
fos= new FileOutputStream(pFile);
bos= new BufferedOutputStream(fos,
BUFFER_SIZE);

while((len= zipis.read(buffer,0,
BUFFER_SIZE) != -1)
bos.write(buffer, 0, len);
bos.flush();
} else {
throw new ExceptionThe zip did not contain
any file)
} // end if
} catch (Exceptione) {
throw e;
} finally {
bos.close();
zipis.close();
fos.close();
fis.close();
} // end try
} // end UnZip

example of use
public static void main(String[] args) throws Exception {
try {
Archivos arch= new Files();
arch.Zippear("devtroce.jpg","devtroce.zip");
SystemCompressed!
arch.UnZip("devtroce.zip","new_devtroce.jpg");
SystemUnzipped!
} catch (Exceptione) {
e.printStackTrace();
}
}
}// end class

Another method

zip file compression code in java without password tutorial

Hello guys, how are you? I hardly found many tutorials while browsing the web.
how to compress files in java with a password and without a password today I will teach you in
various entries on how to compress files without a password and with a password using the
NetBeans platform in Java let's start :)

To compress files, we need to download the following library:

Download library

then we add the .jar library by right-clicking on the library folder --> add
jar file

after that we are going to create a new class I'm going to call it add_a_un_zip and
we added the following code:

import java.io.File;
import java.util.ArrayList;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

/**
*
* @author andres2288
*/
add a file to the zip but can also create the zip from scratch
public class add_a_un_zip {

public add_a_un_zip () {
try {
ZipFile zipFile = new
ZipFile("C:/Users/andres2288/Documents/compression/andres2288.zip");

ArrayList filesToAdd = new ArrayList();


filesToAdd.add(new
File("C:/Users/andres2288/Documents/compression/ZipTest/sample.txt");

ZipParameters parameters = new ZipParameters();


parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
set compression method to deflate compression

parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

zipFile.addFiles(filesToAdd, parameters);

} catch (ZipException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


new add_a_un_zip ();
}
}

We have the default constructor and there we place the code there is an exception catch
but be careful it is not from netbeans it is from the default zip library that's why when creating a
we can make a mistake in the exception since it is not Exception e but rather
It's a ZipException, in the code we use an ArrayList to add how many files.
we want and define parameters of the library to set parameters for compression
such as the level of compression if maximum, normal, or low and that it is constant,
in the part where it says ZipFile zipFile = new
ZipFile("C:/Users/andres2288/Documents/compression/andes2288.zip"); is the path
where the new compressed file will be created or the existing andres2288.zip will be
new file or if it already exists, compress the plain text file inside where it says
filesToAdd.add(new
File("C:/Users/andres2288/Documents/compression/ZipTest/sample.txt"); is the
file to compress can compress anything you want up to a
mp3 file and you can add more files by repeating that line that's all :)
add a folder to a compressed file with java

Well guys, sometimes we need to add a folder that is in the environment of


Windows to a compressed zip file this code is only to add empty folders
In another entry, it is to add a folder with files inside; first, we must
create a new class we are going to call add_only_one_folder
the code is the following and at the end the library for you to download:

import java.io.File;
import java.util.ArrayList;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

/**
*
* @author andres2288
*/
public class add_only_one_folder {
//add external files to the compressed file but creating a folder
desired a chimba
public add_only_one_folder() {
try {
ZipFile zipFile = new
ZipFile("C:/Users/andres2288/Documents/compression/andres2288.zip");

ArrayList filesToAdd = new ArrayList();


filesToAdd.add(new
File("C:/Users/andres2288/Documents/compression/soy_una_carpeta"));

ZipParameters parameters = new ZipParameters();


parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
set compression method to deflate compression

parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

parameters.setRootFolderInZip("agregado/");

zipFile.addFiles(filesToAdd, parameters);
} catch (ZipException e) {
e.printStackTrace();
}

public static void main(String[] args) {


new add_only_one_folder();
}
}

where it says ZipFile zipFile = new


ZipFile("C:/Users/andres2288/Documents/compression/andes2288.zip"); is the
the file to be compressed can start from zero or it may already exist
file where it says filesToAdd.add(new
File("C:/Users/andres2288/Documents/compression/I_am_a_folder");is a
folder that is in the Windows environment and where it says
parameters.setRootFolderInZip("agregado/"); it's a new folder to which you
You can give it any name you want, and you can change it for any.
You can play with that for your respective applications.

code to compress files with password using java

Well guys, here are several entries where we use various functions of this.
library the library at the end I leave you the download link the following code is for
compress files with java and put a password for security only puts it
password for the file that you wish to compress the rest not but however
You can compress the files you want since we use an ArrayList.
You can play with this library; it has several functions, and I will explain them to you.
each entry:
The first thing we need to do is create a new class.
we will call add_a_zip_with_password
and in that class we put the following code:

import java.io.File;
import java.util.ArrayList;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

public class add_a_un_zip_with_password {


public add_a_un_zip_with_password() {

try {
ZipFile zipFile = new
ZipFile("C:/Users/andres2288/Documents/compression/andes2288.zip");

ArrayList filesToAdd = new ArrayList();


filesToAdd.add(new
File("C:/Users/andres2288/Documents/compression/ZipTest/sample.txt");
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); //
set compression method to deflate compression

parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

parameters.setEncryptFiles(true);

parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);

parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);

parameters.setPassword("123");

zipFile.addFiles(filesToAdd, parameters);
} catch (ZipException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new add_a_un_zip_with_password();
}
}

where it says ZipFile zipFile = new


ZipFile("C:/Users/andres2288/Documents/compression/andres2288.zip"); is the
The new file we are going to compress may not exist as it may exist,
where it says
filesToAdd.add(new
File("C:/Users/andres2288/Documents/compression/ZipTest/sample.txt"); is the
the text file that I am going to compress is the path where that file is located
that above will be a plain text file you can compress any you want
you can also add more files by repeating the line, where it says
parameters.setPassword("123"); is the password that we are going to insert for
compress and that's it any questions you can comment on :)

copy files from one place to another with java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFiles {

public static void main(String[] args) {


File origin = new
File("C:\Users\gatu\Desktop\prueba.txt");
Destination file = new
File("C:\Users\gatu\Desktop\arbol\prueba.txt");

try {
InputStream in = new FileInputStream(source);
OutputStream out = new
FileOutputStream(destination);

byte[] buf = new byte[1024];


int len;

while ((len = in.read(buf)) > 0) {


out.write(buf, 0, len);
}

in.close();
out.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}

music player or play music in java


Well, here I will give you a code to play music with Java first.
We create a package called player and inside that package a new class I.
I will call it Player in that class I put the following code:
package player;

import java.io.File;
import javazoom.jlgui.basicplayer.BasicPlayer;

public class Player {


public BasicPlayer player;

public Reproductor() {
player = new BasicPlayer();
}
public void coge(String y){

}
public void Play() throws Exception {
player.play();
}

public void OpenFile(String path) throws Exception {


player.open(new File(path));
}

public void Pause() throws Exception {


player.pause();
}

public void Continue() throws Exception {


player.resume();
}

public void Stop() throws Exception {


player.stop();
}
public void playMp3() throws Exception {
try {
Player my_player = new Player();
my_player.OpenFile("C:/Users/Public/Music/Sample
Music/Kalimba.mp3
my_player.Play();
} catch (Exception ex) {
Error:
}
}
public static void main(String args[]) throws Exception{
Player y = new Player();
OpenFile("C:/Users/Public/Music/Sample Music/Kalimba.mp3");
y.Play();
}
}
then they download these 2 files that are at the bottom and put them or import them
like libraries and ready to make a music player

Crear un archivo comprimido Zip con Java

Compressing certain types of files such as text files can represent a


considerable reduction in the size of the original file, an XML of 20 MiB can be
to remain at 1.5 MiB, that is, a compression rate of 13 or in other words the
compressed file takes up 13 times less. This is very interesting in applications
web as it can help save bandwidth and reduce download times
from the file. The compression comes at the cost of loading the CPU with work but
usually the global time it takes to download the file is usually less
compressing since the main limitation is usually the network bandwidth and not the
CPU load. Another advantage for web applications is that some formats
In addition to compressing, they can contain several files and thus make use of them.
You can return a file but that contains several in a single request.

Java provides aseries of classesto work with compressed files in format


zip and its use is not very complicated. Here is the code to generate a zip file with the
Java API and saving two files in it.

OutputStream os = ...;

ZipOutputStream zos = new ZipOutputStream(os);

zos.putNextEntry(new ZipEntry("File 1.xml"));

zos.write(...);

zos.closeEntry();

zos.putNextEntry(new ZipEntry("File 2.xml"));

zos.write(...);

zos.closeEntry();

zos.close();

Zip in Java: Compress files and/or directories


Clear and concise example to create a zip file with Java libraries. The following
This code also serves to create a zip file of a directory with all its contents.
which is added recursively.
Next, I copy and paste the code as is, but I add the link where I got it from.
I recovered.
001 import java.io.*;
002 import java.util.zip.*;
003
004 /**
005 * Compresses a file or directory into a Zip archive. Users of the
006 * class supply the name of the file or directory as an argument.
007
008 public class SimpleZip {
009
010 private static ZipOutputStream zos;
011
012 public static void main(String[] args) {
User must specify a directory to compress
014
015
016
017
018 if (args.length < 1) {
Usage: java SimpleZip directoryName
System.exit(0);
021 }
//Get the name of the file or directory to compress.
023
024
025
026
027 String fileName = args[0];
//Use the makeZip method to create a Zip archive.
029
030
031 try {
032 makeZip(fileName);
}
//Simply print out any errors we encounter.
035
036
037 catch (Exception e) {
System.err.println(e);
039 }
040 }
041
042 /**
Creates a Zip archive. If the name of the file passed in is a
directory, the directory's contents will be made into a Zip
044
file.
045 */
046 public static void makeZip(String fileName)
047 throws IOException, FileNotFoundException
048 {
049 File file = new File(fileName);
zos = new ZipOutputStream(new FileOutputStream(file +
050
.zip"));
051 //Call recursion.
052
053
054 recurseFiles(file);
055 //We are done adding entries to the zip archive,
056
057
058 //so close the Zip output stream.
059
060
061 zos.close();
}
063
064 /**
065 * Recurses down a directory and its subdirectories to look for
066 * files to add to the Zip. If the current file being looked at
067 * is not a directory, the method adds it to the Zip file.
068 */
private static void recurseFiles(File file)
throws IOException, FileNotFoundException
071 {
072 if (file.isDirectory()) {
//Create an array with all of the files and
073
subdirectories
074 //of the current directory.
075 String[] fileNames = file.list();
076 if (fileNames != null) {
Recursively add each array entry to make sure that we
077
get
subdirectories as well as normal files in the
078
directory.
079 for (int i=0; i<filenames.length; i++){
080 recursefiles(new File(file, fileNames[i]));
081 }
}
}
Otherwise, a file so add it as an entry to the Zip
084
file.
085 else {
086 byte[] buf = new byte[1024];
087 int len;
//Create a new Zip entry with the file's name.
089
090
091 ZipEntry zipEntry = new ZipEntry(file.toString());
//Create a buffered input stream out of the file
093
094
095 //we're trying to add into the Zip archive.
096
097
098 FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin);
100 zos.putNextEntry(zipEntry);
//Read bytes from the file and write into the Zip
101
archive.
102
103
104 while ((len = in.read(buf)) >= 0) {
105 zos.write(buf, 0, len);
}
//Close the input stream.
108
109
110 in.close();
//Close this entry in the Zip stream.
112
113
114 zos.closeEntry();
}
116 }
117 }

The method that performs all the magic is makeZip(String fileName) which creates a zip file.
of the respective file or directory named fileName + ".zip".

I add here the link where this piece of code is retrieved, in addition to making a
Explanation of the use of zip and gzip libraries in Java.Click here(Now ask for you to)
register to be able to access the article.

Something I have had trouble with is creating a jar file using these libraries,
I have not found how to make a jar that is recognized when added to
classpath and run the java application, if someone has an example regarding that, I
I would appreciate any comments.

Create a zip file

Let's look at a simple example of how to create a zip file using Java. For the
For example, we will have a .txt file with a piece of text and we are going to package it in a
file.zip. We will use the classes provided by Java in itsjava.util.zip package

First, we create an OutputStream for our zip file, so that


we can start placing our compressed files in it. This OutputStream is
obtained by instantiating a ZipOutputStream

ZipOutputStream os = new ZipOutputStream(new


FileOutputStream("file.zip");
We can indicate the level and type of compression we want with the methods
setMethod() and setLevel() of the ZipOutputStream class. The values that these accept
parameters. We will leave them at their default values, which are DEFLATED for
setMethod() (is the default algorithm) and setLevel() with
DEFAULT_COMPRESSION, both constants defined in the Deflater class

These are the default options, it is not


// necessary to put them in code.
os.setLevel(Deflater.DEFAULT_COMPRESSION);
os.setMethod(Deflater.DEFLATED);

Once this is done, we just need to start adding files. To do this, the steps to follow are
what to give

Indicate to ZipOutputStream that we are starting a new entry (a new


file
Pass the bytes of that new entry (from the file). They are passed uncompressed and already.
will be responsible for compressing them as we add them.
Indicate to ZipOutputStream that we have finished the new entry.
Repeat the previous steps as long as we want to continue adding files.

To indicate to ZipOutputStream that we are starting to add a new file, we put

ZipEntry entry = new ZipEntry("file.txt");


os.putNextEntry(entry);

The name we use in ZipEntry is the name we want the file to have.
inside the zip. Although it is usual, it does not have to match the name of the
file outside the zip. If we want the compressed file to be inside a
directory in the zip, it will be enough to also put the path where we want it

ZipEntry entry = new ZipEntry("directory/file.txt");


os.putNextEntry(entry);

Now you have to read the normal file and pass the bytes to the ZipOutputStream.

FileInputStream fis = new FileInputStream("file.txt");


byte [] buffer = new byte[1024];
int read=0;
while (0 < (read=fis.read(buffer))){
os.write(buffer, 0, read);
}

We simply open the normal file with a FileOutputStream, create a buffer of


reading 1024 bytes (or the size we consider adequate) and we get into a
loop to read and write in the ZipOutputStream.

Once we have finished reading and inputting bytes from this file, we close both the
file like the zip entry, indicating to ZipOutputStream that we have finished
with this file.

fis.close();
os.closeEntry();
we repeat the process with all the files we want to continue adding, creating
for each of them a new ZipEntry, writing the file bytes and closing
the ZipEntry.

Once we finish with all the files, we simply close the


ZipOutputStream

os.close();

Read and extract a zip file

If we already have the zip file and we want to read its content and extract it,
we will use the ZipInputStream class by passing the zip file

ZipInputStream zis = new ZipInputStream(new


FileInputStream("file.zip");

This class has methods to query how many entries it has, what they are, etc. In this
example that aims to be simple, we are simply going to walk through and extract
all the entries. To go through the entries

ZipEntry entry;
while (null != (input=zis.getNextEntry()) ){
System.out.println(entrada.getName());
...
}

For each ZipEntry, we can interrogate it to know its size, compression format,
etc, etc. Just look at theZipEntry APIto see the possibilities.

We take advantage of the same loop to extract the files.

ZipEntry entry;
while (null != (entry=zis.getNextEntry()) ){
System.out.println(entrada.getName());

FileOutputStream fos = new FileOutputStream(entrada.getName());


int read;
byte [] buffer = new byte[1024];
while (0 < (leido = zis.read(buffer))){
fos.write(buffer, 0, read);
}
fos.close();
zis.closeEntry();
}

For each entry, we create a FileOutputStream where we will write the file.
unzipped. Here we have cheerfully put new
FileOutputStream(entrada.getName()), but in reality we must analyze beforehand
the entrada.getName() to see if it is the name of a valid file that we can
write. For example, if as we saw when writing the zip, the name of the entry were
"directory/file.txt", before opening we should create the directory or we will get a
error.

Then, a read buffer is simply declared and we enter a loop until the end.
from file, reading from the ZipInputStream and writing to the FileOutputStream.
After the transfer is finished, we close the FileOutputStream and inform the ZipInputStream
that we have finished with the entry, calling closeEntry().

And once we exit the loop of entries (no more entries remain in the zip),
we close the ZipOutputStream

zip.close();

You might also like