Compress 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:

Читайте также:  Games with embed html

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 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. "); > >

Источник

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.

Источник

Files Compressing and Decompressing in Java (Zipping and Unzipping)

Twitter Facebook Google Pinterest

A quick guide to compress and decompress the files in java using java built-in api methods in java.util.zip package. Example programs to files zipping and unzipping.

1. Introduction

In this tutorial, We will be learning how to compress a file in java and how to decompress the same compressed file using java java.util.zip package.

Java is built with zipping(archiving) files utilities in java.util.zip which you can find all the zipping and unzipping related utilities.

In this article, we will see how to compress a file, multiple files, and files in folder or directory. At last, we will how to unzip an archived file. All the examples shown are can be done in java 8 or higher versions.

Files Compressing and Decompressing in Java (Zipping and Unzipping)

2. Zipping a single file

Let us see a simple example program on how to zip or compress or archive a file in java using ZipEntry and ZipOutputStream classes. This calss takes input «src-file.txt» and generates a compressed file «compressed.zip» file.

package com.java.w3schools.blog.java.program.to.files; /** * * Java Program to compress a file. * */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZippingAFileExample < public static void main(String[] args) throws IOException < // src file String sourceFile = "src-file.txt"; // compressed file name FileOutputStream fos = new FileOutputStream("compressed.zip"); System.out.println("File compression started."); // output zip file stream. ZipOutputStream zipOut = new ZipOutputStream(fos); File fileToZip = new File(sourceFile); FileInputStream fis = new FileInputStream(fileToZip); // Creating zip file name. ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; // writing content into zip or archieve file. while ((length = fis.read(bytes)) >= 0) < zipOut.write(bytes, 0, length); >zipOut.close(); fis.close(); fos.close(); System.out.println("Done"); > >

3. Zipping Multiple Files in Single Program

In the above program, we have seen only one file compressing technique. But now, let us see the example program to compress a set of files. The below program converts «file-1.txt», «file-2.txt», «file-3.txt» three files into multifilesCompressed.zip file.

package com.java.w3schools.blog.java.program.to.files; /** * * Java Program to compress a multiple files at a time. * */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZippingAFileExample < public static void main(String[] args) throws IOException < // storing the multiple files in arraylist ListsrcFiles = Arrays.asList("file-1.txt", "file-2.txt", "file-3.txt"); // output zipped file FileOutputStream fos = new FileOutputStream("multifilesCompressed.zip"); System.out.println("Zipping started."); ZipOutputStream zipOut = new ZipOutputStream(fos); for (String srcFile : srcFiles) < File fileToZip = new File(srcFile); FileInputStream fis = new FileInputStream(fileToZip); // Creating a zip entry. ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) < zipOut.write(bytes, 0, length); >fis.close(); > zipOut.close(); fos.close(); System.out.println("Done"); > >

4. Zipping A Directory or Folder

Now, let us see how to zip an entire directory using a recursive approach with method a zipFile(). This program converts all have files from the «src» folder into a «DirSrcCompressed.zip» file.

package com.java.w3schools.blog.java.program.to.files; /** * * Java Program to compress a directory at a time. * */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZippingADirectory < public static void main(String[] args) throws IOException < String sourceFile = "src"; FileOutputStream fos = new FileOutputStream("DirSrcCompressed.zip"); ZipOutputStream zipOut = new ZipOutputStream(fos); File fileToZip = new File(sourceFile); zipFile(fileToZip, fileToZip.getName(), zipOut); zipOut.close(); fos.close(); >private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException < if (fileToZip.isHidden()) < return; >if (fileToZip.isDirectory()) < if (fileName.endsWith("/")) < zipOut.putNextEntry(new ZipEntry(fileName)); zipOut.closeEntry(); >else < zipOut.putNextEntry(new ZipEntry(fileName + "/")); zipOut.closeEntry(); >File[] children = fileToZip.listFiles(); for (File childFile : children) < zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); >return; > FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileName); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) < zipOut.write(bytes, 0, length); >fis.close(); > >

Instread of zipping a complete folder, we can zip only .java or .docx or .xml files using listFiles(FilenameFilter filter).

5. Unzipping a compressed file

Example program to unzip a compressed «multifilesCompressed.zip».

package com.java.w3schools.blog.java.program.to.files; /** * * Java Program to unzip a compressed .zip file. * */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class UnzipFile < public static void main(String[] args) < String zipFilePath = "multifilesCompressed.zip"; unzip(zipFilePath); >private static void unzip(String zipFilePath) < File dir = new File("."); // create output directory if it doesn't exist if (!dir.exists()) dir.mkdirs(); FileInputStream fis; // buffer for read and write data to file byte[] buffer = new byte[1024]; try < fis = new FileInputStream(zipFilePath); ZipInputStream zis = new ZipInputStream(fis); ZipEntry ze = zis.getNextEntry(); while (ze != null) < String fileName = ze.getName(); File newFile = new File("." + File.separator + fileName); System.out.println("Unzipping to " + newFile.getAbsolutePath()); // create directories for sub directories in zip new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) >0) < fos.write(buffer, 0, len); >fos.close(); // close this ZipEntry zis.closeEntry(); ze = zis.getNextEntry(); > // close last ZipEntry zis.closeEntry(); zis.close(); fis.close(); > catch (IOException e) < e.printStackTrace(); >> >

This program will be generated three files «file-1.txt», «file-2.txt», «file-3.txt».

6. Possible Exceptions

If the input file does not exists or file name is wrong then will get FileNotFoundException.

Exception in thread "main" java.io.FileNotFoundException: src-file.txt (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:213) at java.base/java.io.FileInputStream.(FileInputStream.java:155) at com.java.w3schools.blog.java.program.to.files.ZippingAFileExample.main(ZippingAFileExample.java:18) 

7. Conclusion

In this article, We have seen working examples of how to compress and decompress files, a set of files and directory.

Источник

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