This post shows how you can zip files in Java. Using the options given here you can zip a single file or more than one file by specifying all those files.
Zip a file in Java
To zip files in Java there are two options-
- Using ZipOutputStream and ZipEntry classes residing in
java.util.zip
package. - Using the Zip File System Provider- The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider was introduced in the JDK 7 release.
Want to zip a folder, check this post How to Zip a Folder in Java
Zipping single fie in Java using ZipOutputStream
The steps for zipping a file using ZipOutputStream are as follows-
- Create an InputStream for reading the source file.
- Create an OutputStream for the zip file and wrap it in a ZipOutputStream object.
- Create a ZipEntry instance for the source file and add it to the ZipOutputStream.
- Read data from the source file and write it to the ZIP file.
- Close the streams.
public class ZipFile { public static void main(String[] args) { // source file String fileName = "F:\\knpcode\\links.txt"; File file = new File(fileName); //Creating zipfile name from fileName by // truncating .txt and appending .zip String zipFilename = fileName.substring(0, fileName.indexOf('.')) + ".zip"; File zipFile = new File(zipFilename); zipFile(file, zipFile); } // Method to zip file private static void zipFile(File file, File zippedFile){ final int BUFFER = 1024; ZipOutputStream zos = null; BufferedInputStream bis = null; try{ FileInputStream fis = new FileInputStream(file); bis = new BufferedInputStream(fis, BUFFER); // Creating ZipOutputStream for writing to zip file FileOutputStream fos = new FileOutputStream(zippedFile); zos = new ZipOutputStream(fos); // Each file in the zipped archive is represented by a ZipEntry // Only source file name is needed ZipEntry ze = new ZipEntry(file.getName()); zos.putNextEntry(ze); byte data[] = new byte[BUFFER]; int count; while((count = bis.read(data, 0, BUFFER)) != -1) { zos.write(data, 0, count); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { zos.close(); bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Zipping single fie in Java using Zip File System Provider
You can use the factory methods of the java.nio.file.FileSystems
class to create a new zip file system or to obtain a
reference to an existing zip file system.
You can create a zip file system by specifying the path of the zip or JAR file in following way-
URI uri = URI.create("jar:file:/PATH/TO/ZIPFILE");
FileSystem fs = FileSystems.newFileSystem(uri, env);
public class ZipFile { public static void main(String[] args) { // source file String fileName = "F:/knpcode/links.txt"; //Creating zipfile name from fileName by // truncating .txt and appending .zip String zipFilename = fileName.substring(0, fileName.indexOf('.')) + ".zip"; zipFile(fileName, zipFilename); } private static void zipFile(String file, String zippedFile){ Map<String, String> env = new HashMap<>(); env.put("create", "true"); // locate file system by using the syntax // defined in java.net.JarURLConnection URI uri = URI.create("jar:file:/" + zippedFile); try (FileSystem zipfs = FileSystems.newFileSystem(uri.normalize(), env)) { Path sourceFile = Paths.get(file); System.out.println("Name-- " + sourceFile.getFileName().toString()); Path pathInZipfile = zipfs.getPath(sourceFile.getFileName().toString()); // copy a file into the zip file Files.copy(sourceFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING ); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Zipping multiple files in Java
Here is an example of zipping multiple files in Java using ZipOutputStream
where each source file is added
as a ZipEntry to the ZipOutputStream.
public class ZipFile { public static void main(String[] args) { try { // source files String file1 = "F:/knpcode/links.txt"; String file2 = "F:/knpcode/Test/postend.txt"; // Zipped file name String zipFilename = "F:/knpcode/result.zip"; File zipFile = new File(zipFilename); // Creating ZipOutputStream for writing to zip file FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); zipFile(file1, zos); zipFile(file2, zos); zos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Method to zip file private static void zipFile(String fileName, ZipOutputStream zos) throws IOException{ final int BUFFER = 1024; BufferedInputStream bis = null; try{ File file = new File(fileName); FileInputStream fis = new FileInputStream(file); bis = new BufferedInputStream(fis, BUFFER); // Each file in the zipped archive is represented by a ZipEntry // Only source file name is needed ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); byte data[] = new byte[BUFFER]; int count; while((count = bis.read(data, 0, BUFFER)) != -1) { zos.write(data, 0, count); } zos.closeEntry(); } finally{ try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
That's all for the topic How to Zip Files in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like
- How to Unzip a File in Java
- Creating Password Protected Zip File in Java
- Java Program to Remove Duplicate Elements From an Array
- Stable or Unstable Number Java Program
- Read Excel File in Java Using Apache POI
- HashMap Vs ConcurrentHashMap in Java
- Java String intern() Method
- Constructor Dependency Injection in Spring
- Distributed Cache in Hadoop
- fnmatch Module in Python - File Name Pattern Matching
No comments:
Post a Comment