- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compressing and Decompressing files in Java
Reading data of a particular file and and compress some files into a zip, is a process of encapsulation in Java. There are two compressing and decompressing classes in a Java environment, which provides the data deflate compression format. They are −
DeflaterOutputStream class − used to compress the files into a deflate format such as GZIPOutputStream.
InflaterInputStream class − used to decompress the files in a deflate format such as GZIPInputStream.
Here is an example of the process how we can compress a file into a Zip file in Java −
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); }
Algorithm to Perform Compressing and Decompressing Files in Java
In this possible algorithm, we are going to show you how to perform the compressing and decompressing process to get the desired result by using a Java environment.
Step 1 − Start the process.
Step 2 − Declare and import the Java packages to perform the Zipping and Unzipping process.
Step 3 − Declare a public class.
Step 4 − Declare a string argument.
Step 5 − Assign the original files which can throw an exception.
Step 6 − Declare a FileInputStream to perform the reading data operation.
Step 7 − Assign the second compressed file.
Step 8 − Declare a FileOutputStream to perform the reading data operation.
Step 9 − Read the data from the FileInputStream.
Step 10 − Write the data into the DeflaterOutputStream.
Step 11 − Get the output as compressed and decompressed file.
Step 12 − Close the files.
Step 13 − Get the return values.
Step 14 − Terminate the process.
Syntax to Compressing and Decompressing Files in Java
public class CompressingFiles { public static void main(String args[]) throws IOException { String inputPath = "Declare The File Path Input"; FileInputStream inputStream = new FileInputStream(inputPath); String outputPath = "Declare The File Path Output"; FileOutputStream outputStream = new FileOutputStream(outputPath); DeflaterOutputStream compresser = new DeflaterOutputStream(outputStream); int contents; while ((contents=inputStream.read())!=-1){ compresser.write(contents); } compresser.close(); System.out.println("File compressed Today....."); } public class DeCompressingFiles { public static void main(String args[]) throws IOException { StringinputPath ="Declare The File Path Input"; FileInputStream inputStream = new FileInputStream(inputPath); String outputpath = "Declare The File Path Output"; FileOutputStream outputStream = new FileOutputStream(outputpath); InflaterInputStream decompresser = new InflaterInputStream(inputStream); int contents; while ((contents=decompresser.read())!=-1){ outputStream.write(contents); } outputStream.close(); decompresser.close(); System.out.println("File un-compressed today"); } }
In this possible syntax above, we have tried to show you how to declare and create a compressing and decompressing class and get the zip file as a result. By using these particular syntax, we are heading towards the possible Java approaches to solve the problem statement in an efficient manner.
Approaches to Follow
Approach 1 − Java program to compress a File using DeflaterOutputStream and decompress it by using InflaterInputStream
Approach 2 − Java programs to run the compress and decompress operation on a single file and, multiple files
Approach 1: to Compress a File Using DeflaterOutputStream and Decompress it by Using InflaterInputStream
Use of DeflaterOutputStream Method to Compress a File
In this possible approach, we are going to apply the DeflaterOutputStream which is able to compress the files into a deflate format.
DeflaterOutputStream dos=new DeflaterOutputStream(fos); InflaterInputStream iis=new InflaterInputStream(fis)
Example
//Java program to crompress some files by using java.util.zip.DeflaterOutputStream import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; public class zipoperation{ public static void main(String[] args) throws IOException { FileInputStream fis=new FileInputStream("File 1 ARBRDD"); FileOutputStream fos=new FileOutputStream("File 2 ARBRDD"); DeflaterOutputStream dos=new DeflaterOutputStream(fos); int data; while ((data=fis.read())!=-1){ dos.write(data); } fis.close(); dos.close(); } }
Exception in thread "main" java.io.FileNotFoundException: File 1 ARBRDD (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112) at zipoperation.main(zipoperation.java:10)
Use of InflaterInputStream Method to Decompress a File
In this possible approach, we are going to apply the InflaterInputStream, which is able to decompress the files into a deflate format.
Example
//Java program to crompress some files by using java.util.zip.InflaterInputStream import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.InflaterInputStream; public class unzipARBRDD{ public static void main(String[] args) throws IOException { FileInputStream fis=new FileInputStream("File 2 ARBRDD"); FileOutputStream fos=new FileOutputStream("File 3 ARBRDD"); InflaterInputStream iis=new InflaterInputStream(fis); int data; while((data=iis.read())!=-1){ fos.write(data); } fos.close(); iis.close(); } }
Output
Exception in thread "main" java.io.FileNotFoundException: File 2 ARBRDD (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112) at unzipARBRDD.main(unzipARBRDD.java:9)
Disclaimer − Each and every Java code mentioned here above, the user will get exception when they run this code. The mentioned exceptions are here just for the file path, which is an unique statement for every user and his/her system.
Approach 2: to run the Compress and Decompress Operation on a Single File and, Multiple
Use of the Various Stream Methods
In this possible approach,we are going to apply the input output streams present in a Java environment, on multiple file and as well as on the directory files too. After running these Java approaches we will get the desired output in a formation of Zip files.
FileInputStream fin=new FileInputStream("File Name.java"); FileOutputStream fout=new FileOutputStream("Compressed File.txt");
Example 1
//Java Program to compress a single file with input output stream 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 { String sourceFile = "src-file.txt"; FileOutputStream fos = new FileOutputStream("compressed.zip"); System.out.println("File compression started."); ZipOutputStream zipOut = new ZipOutputStream(fos); File fileToZip = new File(sourceFile); FileInputStream fis = new FileInputStream(fileToZip); 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); } zipOut.close(); fis.close(); fos.close(); System.out.println("Done"); } }
Output
File compression started. 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:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at ZippingAFileExample.main(ZippingAFileExample.java:15)
Example 2
//Java Program to compress a multiple files at a time in Single Program 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 ARBRDD{ public static void main(String[] args) throws IOException { List<String> srcFiles = Arrays.asList("file-1.txt", "file-2.txt", "file- 3.txt"); 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); 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"); } }
Output
Zipping started. Exception in thread "main" java.io.FileNotFoundException: file-1.txt (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at ARBRDD.main(ARBRDD.java:18)
Example 3
//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 ARBRDD { 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(); } }
Output
Exception in thread "main" java.io.FileNotFoundException: src (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at ARBRDD.zipFile(ARBRDD.java:37) at ARBRDD.main(ARBRDD.java:14)
Example 4
//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 UnzipFileARBRDD { public static void main(String[] args) { String zipFilePath = "multifilesCompressed.zip"; unzip(zipFilePath); } private static void unzip(String zipFilePath) { File dir = new File("."); if (!dir.exists()) dir.mkdirs(); FileInputStream fis; 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()); 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(); zis.closeEntry(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
Output
java.io.FileNotFoundException: multifilesCompressed.zip (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112) at UnzipFileARBRDD.unzip(UnzipFileARBRDD.java:20) at UnzipFileARBRDD.main(UnzipFileARBRDD.java:11)
Disclaimer − Each and every Java code mentioned here above, the user will get exception when they run this code. The mentioned exceptions are here just for the file path, which is an unique statement for every user and his/her system.
Conclusion
In a Java environment, the DeflaterOutputStream and InflaterInputStream classes has been introduced to compress and decompress the file contents, which provides the useful methods that can be used for compressing the file content in a ZIP file. Today in this article, we have learned about the zipping operations by using the Java functions. With the above mentioned syntax and Java approches and algorithm, we have tried to solve the problem statement in an efficient manner.