Compressing file in java

How to compress files in GZIP in Java

Here in this tutorial, we will show you how you can easily compress files in GZIP in Java. As per the definition of GZIP in Wikipedia, GZIP is normally used to compress a single file. But we can compress multiple files by adding them in a tarball (.tar) before we compress them into a GZIP file.

Compress Single File to GZIP in Java

For this single file compression, we don’t need to add any libraries or dependencies in our Project. The API is already available in the JDK.

Below is a sample code on how you can compress a file in GZIP using the GZIPOutputStream in Java.

public static void compressGZip(Path fileToCompress, Path outputFile) throws IOException < try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(Files.newOutputStream(outputFile))) < byte[] allBytes = Files.readAllBytes(fileToCompress); gzipOutputStream.write(allBytes); >>

To test this, we just simply call this method and pass the file we want to compress and the destination GZIP file. The below code tries to compress our pom.xml file in our project directory.

Path fileToCompress = Paths.get("pom.xml"); Path outputFile = Paths.get("pom.xml.gzip"); compressGZip(fileToCompress, outputFile);

This creates a new file in our project directory:

Читайте также:  Java convert array of objects to string

Decompress GZIP in Java

To decompress, we will be using the GZIPInputStream and copy the contents to the output stream.

public static void decompressGZip(Path fileToDecompress, Path outputFile) throws IOException < try (GZIPInputStream gzipInputStream = new GZIPInputStream(Files.newInputStream(fileToDecompress))) < Files.copy(gzipInputStream, outputFile); >>

And to test this, we will run the code below to decompress our previously created GZIP file.

Path output = Paths.get("pom2.xml"); Path input = Paths.get("pom.xml.gzip"); decompressGZip(input, output);

This in turn will decompress the pom.xml.gzip file to pom2.xml file.

Compress Multiple Files in GZIP in Java

Since GZIP is used to compress single files, we cannot just add files in GZIP and compress it. We need to first create a tarball file which contains the multiple files that we want to compress.

Java doesn’t include API to create a .tar file. Thus, we will be using the Apache Commons Compress library in our project.

To start with, add first the dependency in your project. If you are using maven, add the below code to your pom.xml file:

 org.apache.commons commons-compress 1.20  

And here is the sample code on how we can use it to create the tarball file and compress it to GZIP.

public void compressTarGzip(Path outputFile, Path. inputFiles) throws IOException < try (OutputStream outputStream = Files.newOutputStream(outputFile); GzipCompressorOutputStream gzipOut = new GzipCompressorOutputStream(outputStream); TarArchiveOutputStream tarOut = new TarArchiveOutputStream(gzipOut)) < for (Path inputFile : inputFiles) < TarArchiveEntry entry = new TarArchiveEntry(inputFile.toFile()); tarOut.putArchiveEntry(entry); Files.copy(inputFile, tarOut); tarOut.closeArchiveEntry(); >tarOut.finish(); > >

To test this, we just need to pass the output file path for our .tar.gz file and the list of paths that we want to compress.

Path tarGZOut = Paths.get("tarball.tar.gz"); compressTarGzip(tarGZOut, Paths.get("pom.xml"), Paths.get("compress-file-example.iml"));

In our above code, we wanted to compress both our pom.xml file and our .iml file in our project directory. Running this code creates our tarball.tar.gz file.

Decompress a TAR.GZ file in Java

To decompress our .tar.gz file that contains multiple files, we will just need to iterate each archive entry in our GZIP file and save it to our destination. Here’s how you can do it:

public void decompressTarGzip(Path fileToDecompress, Path outputDir) throws IOException < try(InputStream inputStream = Files.newInputStream(fileToDecompress); GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(inputStream); TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) < ArchiveEntry entry; while ((entry = tarIn.getNextEntry()) != null) < Path outputFile = outputDir.resolve(entry.getName()); //save to output directory Files.copy(tarIn, outputFile); >> >

And for example, if we wanted to decompress our earlier tarball.tar.gz file, we can easily do that using the code below. Note that I created first a folder on which the extract files will be saved.

Files.createDirectory(Paths.get("tar")); decompressTarGzip(Paths.get("tarball.tar.gz"), Paths.get("tar"));

And this results to creating a folder named tar inside our project directory and the files that were extracted:

And that concludes our tutorial on how we can compress files in GZIP in Java. The next tutorial is how you can compress files in Zip in Java.

Источник

How to compress files in ZIP format in Java

In this tutorial, you will learn how to compress files in ZIP format using the java.util.zip package. You know, Java has great support for writing and reading ZIP files via the easy-to-use API. With this feature, you can compress/decompress data on the fly in your Java programs.

1. Steps to Compress a File in Java

  • Open a ZipOutputStream that wraps an OutputStream like FileOutputStream . The ZipOutputStream class implements an output stream filter for writing in the ZIP file format.
  • Put a ZipEntry object by calling the putNextEntry(ZipEntry) method on the ZipOutputStream . The ZipEntry class represents an entry of a compressed file in the ZIP file.
  • Read all bytes from the original file by using the Files.readAllBytes(Path) method.
  • Write all bytes read to the output stream using the write(byte[] bytes, int offset, int length) method.
  • Close the ZipEntry .
  • Close the ZipOutputStream .
  • setMethod(int method) : there are 2 methods: DEFLATED (the default) which compresses the data; and STORED which doesn’t compress the data (archive only).
  • setLevel(int level) : sets the compression level ranging from 0 to 9 (the default).

2. Compress a Single File Example

import java.io.*; import java.nio.file.*; import java.util.zip.*; /** * This Java program demonstrates how to compress a file in ZIP format. * * @author www.codejava.net */ public class ZipFile < private static void zipFile(String filePath) < try < File file = new File(filePath); String zipFileName = file.getName().concat(".zip"); FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); zos.putNextEntry(new ZipEntry(file.getName())); byte[] bytes = Files.readAllBytes(Paths.get(filePath)); zos.write(bytes, 0, bytes.length); zos.closeEntry(); zos.close(); >catch (FileNotFoundException ex) < System.err.format("The file %s does not exist", filePath); >catch (IOException ex) < System.err.println("I/O error: " + ex); >> public static void main(String[] args) < String filePath = args[0]; zipFile(filePath); >>

3. Compress Multiple Files Example

The following program compresses multiple files into a single ZIP file. The file paths are passed from the command line, and the ZIP file name is name of the first file followed by the .zip extension. Here’s the code:

import java.io.*; import java.nio.file.*; import java.util.zip.*; /** * This Java program demonstrates how to compress multiple files in ZIP format. * * @author www.codejava.net */ public class ZipFiles < private static void zipFiles(String. filePaths) < try < File firstFile = new File(filePaths[0]); String zipFileName = firstFile.getName().concat(".zip"); FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); for (String aFile : filePaths) < zos.putNextEntry(new ZipEntry(new File(aFile).getName())); byte[] bytes = Files.readAllBytes(Paths.get(aFile)); zos.write(bytes, 0, bytes.length); zos.closeEntry(); >zos.close(); > catch (FileNotFoundException ex) < System.err.println("A file does not exist: " + ex); >catch (IOException ex) < System.err.println("I/O error: " + ex); >> public static void main(String[] args) < zipFiles(args); >>
java ZipFiles doc1.txt doc2.txt doc3.txt

4. Compress a Whole Directory Example

Using the walk file tree feature of Java NIO, you can write a program that compresses a whole directory (including sub files and sub directories) with ease. The following is source code of such a program:

import java.io.*; import java.nio.file.*; import java.util.zip.*; import java.nio.file.attribute.*; /** * This Java program demonstrates how to compress a directory in ZIP format. * * @author www.codejava.net */ public class ZipDir extends SimpleFileVisitor  < private static ZipOutputStream zos; private Path sourceDir; public ZipDir(Path sourceDir) < this.sourceDir = sourceDir; >@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) < try < Path targetFile = sourceDir.relativize(file); zos.putNextEntry(new ZipEntry(targetFile.toString())); byte[] bytes = Files.readAllBytes(file); zos.write(bytes, 0, bytes.length); zos.closeEntry(); >catch (IOException ex) < System.err.println(ex); >return FileVisitResult.CONTINUE; > public static void main(String[] args) < String dirPath = args[0]; Path sourceDir = Paths.get(dirPath); try < String zipFileName = dirPath.concat(".zip"); zos = new ZipOutputStream(new FileOutputStream(zipFileName)); Files.walkFileTree(sourceDir, new ZipDir(sourceDir)); zos.close(); >catch (IOException ex) < System.err.println("I/O Error: " + ex); >> >
java ZipDir JavaTutorials

API References:

Other Java File IO Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Comments

Hi author, this code didn’t work for me because String zipFileName = dirPath.concat(«.zip»); will only produce a file name, no the full path to the file. This causes OutputStream to error out with file not found. The code that worked for me was String zipFileName = filePath.concat(«.zip»); which reconstructs the input argument AND retains the full path to the file.

Источник

How to compress a file in Java?

The DeflaterOutputStream class of Java is used to compress the given data and stream it out to the destination.

The write() method of this class accepts the data (in integer and byte format), compresses it and, writes it to the destination of the current DeflaterOutputStream object. To compress a file using this method &Minus;

  • Create a FileInputStream object, by passing the path of the file to be compressed in String format, as a parameter to its constructor.
  • Create a FileOutputStream object, by passing the path of the output file, in String format, as a parameter to its constructor.
  • Create a DeflaterOutputStream object, by passing the above created FileOutputStream object, as a parameter to its constructor.
  • Then, read the contents of the input file and write using the write() method of the DeflaterOutputStream class.

Example

import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.DeflaterOutputStream; public class CompressingFiles < public static void main(String args[]) throws IOException < //Instantiating the FileInputStream String inputPath = "D:\ExampleDirectory\logo.jpg"; FileInputStream inputStream = new FileInputStream(inputPath); //Instantiating the FileOutputStream String outputPath = "D:\ExampleDirectory\compressedLogo.txt"; FileOutputStream outputStream = new FileOutputStream(outputPath); //Instantiating the DeflaterOutputStream DeflaterOutputStream compresser = new DeflaterOutputStream(outputStream); int contents; while ((contents=inputStream.read())!=-1)< compresser.write(contents); >compresser.close(); System.out.println("File compressed. "); > >

Источник

Java GZIP Example — Compress and Decompress File

Java GZIP Example - Compress and Decompress File

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Welcome to Java GZIP example. GZIP is one of the favorite tool to compress file in Unix systems. We can compress a single file in GZIP format but we can’t compress and archive a directory using GZIP like ZIP files.

Java GZIP

GZIP, Java GZIP Example

Here is a simple java GZIP example program showing how can we compress a file to GZIP format and then decompress the GZIP file to create a new file. GZIPExample.java

package com.journaldev.files; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GZIPExample < public static void main(String[] args) < String file = "/Users/pankaj/sitemap.xml"; String gzipFile = "/Users/pankaj/sitemap.xml.gz"; String newFile = "/Users/pankaj/new_sitemap.xml"; compressGzipFile(file, gzipFile); decompressGzipFile(gzipFile, newFile); >private static void decompressGzipFile(String gzipFile, String newFile) < try < FileInputStream fis = new FileInputStream(gzipFile); GZIPInputStream gis = new GZIPInputStream(fis); FileOutputStream fos = new FileOutputStream(newFile); byte[] buffer = new byte[1024]; int len; while((len = gis.read(buffer)) != -1)< fos.write(buffer, 0, len); >//close resources fos.close(); gis.close(); > catch (IOException e) < e.printStackTrace(); >> private static void compressGzipFile(String file, String gzipFile) < try < FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(gzipFile); GZIPOutputStream gzipOS = new GZIPOutputStream(fos); byte[] buffer = new byte[1024]; int len; while((len=fis.read(buffer)) != -1)< gzipOS.write(buffer, 0, len); >//close resources gzipOS.close(); fos.close(); fis.close(); > catch (IOException e) < e.printStackTrace(); >> > 
java.util.zip.ZipException: Not in GZIP format at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:164) at java.util.zip.GZIPInputStream.(GZIPInputStream.java:78) at java.util.zip.GZIPInputStream.(GZIPInputStream.java:90) at com.journaldev.files.GZIPExample.decompressGzipFile(GZIPExample.java:25) at com.journaldev.files.GZIPExample.main(GZIPExample.java:18) 

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью