Java compress to gzip

How to Compress a File in GZIP Format

The below code would compress a specified file to GZip format. In the below example we have a text file in B drive under “Java” Folder and we are compressing and generating the GZip file in the same folder.

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream; public class GZipExample < public static void main( String[] args ) < GZipExample zipObj = new GZipExample(); zipObj.gzipMyFile(); >public void gzipMyFile() < byte[] buffer = new byte[1024]; try< //Specify Name and Path of Output GZip file here GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream("B://Java/Myfile.gz")); //Specify location of Input file here FileInputStream fis = new FileInputStream("B://Java/Myfile.txt"); //Reading from input file and writing to output GZip file int length; while ((length = fis.read(buffer)) >0) < /* public void write(byte[] buf, int off, int len): * Writes array of bytes to the compressed output stream. * This method will block until all the bytes are written. * Parameters: * buf - the data to be written * off - the start offset of the data * len - the length of the data */ gos.write(buffer, 0, length); >fis.close(); /* public void finish(): Finishes writing compressed * data to the output stream without closing the * underlying stream. */ gos.finish(); gos.close(); System.out.println("File Compressed!!"); >catch(IOException ioe) < ioe.printStackTrace(); >> >

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

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

Источник

Читайте также:  Чем отличается xhtml от html

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:

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.

Читайте также:  Php интерфейс и трейт

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.

Источник

Java GZIP Example – compress and decompress a file using Java

In this tutorial we demonstrate how to use GZIP to compress and decompress a file. Gzip is a file format and a software application used for file compression and decompression. GZIP is used to reduce the bytes of a file/text/stream. You’re able to compress a single file in GZIP format but you cannot compress and archive a directory like ZIP files using GZIP.

Project Structure

java-gzip-example-compress-decompress-project-structure

Compress and Decompress GZIP file using Java

  • Compress GZIP file: We use the GZIPOutputStream to write the compressed GZIP file.
  • Decompress GZIP file: We use the GZIPInputStream to read the compressed GZIP file.
package com.memorynotfound.resource; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GzipJava < private GzipJava() <>public static void compressGZIP(File input, File output) throws IOException < try (GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(output)))< try (FileInputStream in = new FileInputStream(input))< byte[] buffer = new byte[1024]; int len; while((len=in.read(buffer)) != -1)< out.write(buffer, 0, len); >> > > public static void decompressGzip(File input, File output) throws IOException < try (GZIPInputStream in = new GZIPInputStream(new FileInputStream(input)))< try (FileOutputStream out = new FileOutputStream(output))< byte[] buffer = new byte[1024]; int len; while((len = in.read(buffer)) != -1)< out.write(buffer, 0, len); >> > > >

Compress and Decompress GZIP file using Apache

You can also use org.apache.commons:commons-compress dependency to compress and decompress to and from GZIP formats.

 org.apache.commons commons-compress 1.14 

We can use the IOUtils.copy(in, out) to copy an InputSteam to the OutputStream .

  • Compress file to GZIP format: We use the GzipCompressorOutputStream to compress the specified file.
  • Decompress GZIP file: We use the GzipCompressorInputStream to decompress the compressed GZIP file.
package com.memorynotfound.resource; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import org.apache.commons.compress.utils.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class GzipApache < private GzipApache() <>public static void compressGZIP(File input, File output) throws IOException < try (GzipCompressorOutputStream out = new GzipCompressorOutputStream(new FileOutputStream(output)))< IOUtils.copy(new FileInputStream(input), out); >> public static void decompressGZIP(File input, File output) throws IOException < try (GzipCompressorInputStream in = new GzipCompressorInputStream(new FileInputStream(input)))< IOUtils.copy(in, new FileOutputStream(output)); >> > 

Java GZIP Program

package com.memorynotfound.resource; import java.io.File; import java.io.IOException; public class GzipProgram < public static void main(String. args) throws IOException < // class for resource classloading Class clazz = GzipApache.class; // create files to read and write File example = new File(clazz.getResource("/example.xml").getFile()); File output = new File("/tmp/example.xml.gz"); File decompressed = new File("/tmp/decompressed.xml"); // Java GZIP example compression decompression GzipJava.compressGZIP(example, output); GzipJava.decompressGzip(output, decompressed); // Apache GZIP example compression decompression GzipApache.compressGZIP(example, output); GzipApache.decompressGZIP(output, decompressed); >>

Example Output

You can see that the application created two files. The example.xml.gz is the compressed file in GZIP format. You can see that this file is smaller than the original file. The decompressed.xml file is the result of the decompression.

Читайте также:  1000 7 на питоне код

java-gzip-example-compress-decompress-example-output

References

Источник

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Sunday, April 24, 2022

Compress And Decompress File Using GZIP Format in Java

In this post we’ll see how to use GZIP to compress and decompress a file in Java. You will mainly use GZIP tool to compress and decompress files in Unix systems. Here note that you can only compress a single file using GZIP not multiple files residing in a folder.

Steps to gzip a file

In order to compress a file using GZIP in Java the steps are as follows-

  1. For reading the source file (file which has to be GZIPped) create a FileInputStream.
  2. Create a FileOutputStream to the target file (output GZIPped file).
  3. Create a GZIPOutputStream wrapping the FileOutputStream.
  4. Then you just need to read from the input stream and write to the output stream.

Steps to decompress a file

In order to decompress a file using GZIP in Java the steps are as follows-

  1. For reading the compressed file create a FileInputStream.
  2. Wrap that FileInputStream with in a GZIPInputStream.
  3. Create a FileOutputStream to the new file (created on decompressing GZIP file).
  4. Then you just need to read from the input stream and write to the output stream.

Java example for compressing and decompressing file in GZIP format

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GZipDemo < public static void main(String[] args) < // Path to file which is gzipped String SOURCE_FILE = "G:\\Test\\abc.txt"; // Path to gzipped output files String GZIP_OUTPUT_FILE = "G:\\Test\\abc.gz"; // File you get after decompressings String GZIP_NEW_FILE = "G:\\Test\\newabc.txt"; GZipDemo gZipDemo = new GZipDemo(); try < // Compressing a file gZipDemo.compressGZipFile(SOURCE_FILE, GZIP_OUTPUT_FILE); // decompressing a file gZipDemo.deCompressGZipFile(GZIP_OUTPUT_FILE, GZIP_NEW_FILE); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> /** * Method to gzip a file * @param sourceFile * @param outputFile * @throws IOException */ public void compressGZipFile(String sourceFile, String outputFile) throws IOException < FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(outputFile); GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(fos); byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) >0) < gZIPOutputStream.write(buffer, 0, len); >// Keep it in finally fis.close(); gZIPOutputStream.close(); > /** * Method to decompress a gzip file * @param gZippedFile * @param newFile * @throws IOException */ public void deCompressGZipFile(String gZippedFile, String newFile) throws IOException < FileInputStream fis = new FileInputStream(gZippedFile); GZIPInputStream gZIPInputStream = new GZIPInputStream(fis); FileOutputStream fos = new FileOutputStream(newFile); byte[] buffer = new byte[1024]; int len; while((len = gZIPInputStream.read(buffer)) >0) < fos.write(buffer, 0, len); >// Keep it in finally fos.close(); gZIPInputStream.close(); > >

That’s all for this topic Compress And Decompress File Using GZIP Format in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

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