- Zipping and Unzipping in Java
- 1. Zip a File
- 2. Zip Multiple Files / Directories Java8
- 2. Zip Multiple Files / Directories Java7
- 3. Unzip Directory
- Zipping files using java
- ZipOutputStream. Запись архивов
- Чтение архивов. ZipInputStream
- Tech Tutorials
- Saturday, June 12, 2021
- Zipping Files And Folders in Java
- Steps to zip a file in Java
- Java Program to zip a single file
- Java Program to zip multiple files
- Zipping Directory recursively in Java
- Zipping Directory recursively in Java Using Files.walkFileTree()
- Java code to zip files recursively using list() method
- Zipping files using java
- ZipOutputStream. Запись архивов
- Чтение архивов. ZipInputStream
Zipping and Unzipping in Java
In this post, we will learn Zipping and Unzipping in Java using java.util.zip API. We will also discuss some third-party API to perform these tasks.
1. Zip a File
We will be performing a simple operation to zip a single file into an archive.
public class ZipSingleFile < public static void main(String[] args) throws IOException < String sourceFile = "/Users/umesh/personal/tutorials/source/index.html"; String zipName="/Users/umesh/personal/tutorials/source/testzip.zip"; File targetFile = new File(sourceFile); ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipName)); zipOutputStream.putNextEntry(new ZipEntry(targetFile.getName())); FileInputStream inputStream = new FileInputStream(targetFile); final byte[] buffer = new byte[1024]; int length; while((length = inputStream.read(buffer)) >= 0) < zipOutputStream.write(buffer, 0, length); >zipOutputStream.close(); inputStream.close(); > >
2. Zip Multiple Files / Directories Java8
Creating zip for a single file is not very interesting or real life solution, we will be improving our program with an option to zip entire directory using Files.walk method.
public class ZipDirectory < public static void main(String[] args) throws IOException < String sourceDirectoryPath = "/Users/umesh/personal/tutorials/source"; String zipFilePath = "/Users/umesh/personal/tutorials/source.zip"; zipDirectory(sourceDirectoryPath, zipFilePath); >public static void zipDirectory(String sourceDirectoryPath, String zipPath) throws IOException < Path zipFilePath = Files.createFile(Paths.get(zipPath)); try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFilePath))) < Path sourceDirPath = Paths.get(sourceDirectoryPath); Files.walk(sourceDirPath).filter(path ->!Files.isDirectory(path)) .forEach(path -> < ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString()); try < zipOutputStream.putNextEntry(zipEntry); zipOutputStream.write(Files.readAllBytes(path)); zipOutputStream.closeEntry(); >catch (Exception e) < System.err.println(e); >>); > > >
2. Zip Multiple Files / Directories Java7
public class ZipDirectoryFilesWalk < public static void main(String[] args) throws IOException < Path sourceDirectoryPath = Paths.get("/Users/umesh/personal/tutorials/source"); Path zipFilePath = Paths.get("/Users/umesh/personal/tutorials/source.zip"); zipDirectory(sourceDirectoryPath, zipFilePath); >public static void zipDirectory(Path sourceDirectory, Path zipFilePath) throws IOException < try (FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath.toFile()); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream) ) < Files.walkFileTree(sourceDirectory, new SimpleFileVisitor() < @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException < zipOutputStream.putNextEntry(new ZipEntry(sourceDirectory.relativize(file).toString())); Files.copy(file, zipOutputStream); zipOutputStream.closeEntry(); return FileVisitResult.CONTINUE; >@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException < zipOutputStream.putNextEntry(new ZipEntry(sourceDirectory.relativize(dir).toString() + "/")); zipOutputStream.closeEntry(); return FileVisitResult.CONTINUE; >>); > > >
In the above examples, we saw different options to Zipping Files and Directories in Java using Java7 and Java8.
3. Unzip Directory
public class UnZipDirectory < public static void main(String[] args) throws IOException < String unzipLocation = "/Users/umesh/personal/tutorials/unzip"; String zipFilePath = "/Users/umesh/personal/tutorials/source.zip"; unzip(zipFilePath, unzipLocation); >public static void unzip(final String zipFilePath, final String unzipLocation) throws IOException < if (!(Files.exists(Paths.get(unzipLocation)))) < Files.createDirectories(Paths.get(unzipLocation)); >try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) < ZipEntry entry = zipInputStream.getNextEntry(); while (entry != null) < Path filePath = Paths.get(unzipLocation, entry.getName()); if (!entry.isDirectory()) < unzipFiles(zipInputStream, filePath); >else < Files.createDirectories(filePath); >zipInputStream.closeEntry(); entry = zipInputStream.getNextEntry(); > > > public static void unzipFiles(final ZipInputStream zipInputStream, final Path unzipFilePath) throws IOException < try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(unzipFilePath.toAbsolutePath().toString()))) < byte[] bytesIn = new byte[1024]; int read = 0; while ((read = zipInputStream.read(bytesIn)) != -1) < bos.write(bytesIn, 0, read); >> > >
In this post, we learned how to zip and unzip files or directory using core Java features. Read our articles List all files from a directory in Java to learn how to recursively transverse folders to zip multiple files.
If you want more sophisticated API to perform other operation on the zip files, you can check following open source libraries
All the code of this article is available Over on Github. This is a Maven-based project.
Zipping files using java
Кроме общего функционала для работы с файлами Java предоставляет функциональность для работы с таким видом файлов как zip-архивы. Для этого в пакете java.util.zip определены два класса — ZipInputStream и ZipOutputStream
ZipOutputStream. Запись архивов
Для создания архива используется класс ZipOutputStream. Для создания объекта ZipOutputStream в его конструктор передается поток вывода:
ZipOutputStream(OutputStream out)
Для записи файлов в архив для каждого файла создается объект ZipEntry , в конструктор которого передается имя архивируемого файла. А чтобы добавить каждый объект ZipEntry в архив, применяется метод putNextEntry() .
import java.io.*; import java.util.zip.*; public class Program < public static void main(String[] args) < String filename = "notes.txt"; try(ZipOutputStream zout = new ZipOutputStream(new FileOutputStream("output.zip")); FileInputStream fis= new FileInputStream(filename);) < ZipEntry entry1=new ZipEntry("notes.txt"); zout.putNextEntry(entry1); // считываем содержимое файла в массив byte byte[] buffer = new byte[fis.available()]; fis.read(buffer); // добавляем содержимое к архиву zout.write(buffer); // закрываем текущую запись для новой записи zout.closeEntry(); >catch(Exception ex) < System.out.println(ex.getMessage()); >> >
После добавления объекта ZipEntry в поток нам также надо добавить в него и содержимое файла. Для этого используется метод write, записывающий в поток массив байтов: zout.write(buffer); . В конце надо закрыть ZipEntry с помощью метода closeEntry() . После этого можно добавлять в архив новые файлы — в этом случае все вышеописанные действия для каждого нового файла повторяются.
Чтение архивов. ZipInputStream
Для чтения архивов применяется класс ZipInputStream . В конструкторе он принимает поток, указывающий на zip-архив:
ZipInputStream(InputStream in)
Для считывания файлов из архива ZipInputStream использует метод getNextEntry() , который возвращает объект ZipEntry . Объект ZipEntry представляет отдельную запись в zip-архиве. Например, считаем какой-нибудь архив:
import java.io.*; import java.util.zip.*; public class Program < public static void main(String[] args) < try(ZipInputStream zin = new ZipInputStream(new FileInputStream("output.zip"))) < ZipEntry entry; String name; while((entry=zin.getNextEntry())!=null)< name = entry.getName(); // получим название файла System.out.printf("File name: %s \n", name); // распаковка FileOutputStream fout = new FileOutputStream("new" + name); for (int c = zin.read(); c != -1; c = zin.read()) < fout.write(c); >fout.flush(); zin.closeEntry(); fout.close(); > > catch(Exception ex) < System.out.println(ex.getMessage()); >> >
ZipInputStream в конструкторе получает ссылку на поток ввода. И затем в цикле выводятся все файлы и их размер в байтах, которые находятся в данном архиве.
Затем данные извлекаются из архива и сохраняются в новые файлы, которые находятся в той же папке и которые начинаются с «new».
Tech Tutorials
Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.
Saturday, June 12, 2021
Zipping Files And Folders in Java
In this post we’ll see how to zip files in Java and also how to zip a directory in Java where files and sub-directories are compressed recursively.
In Java, java.util.zip package provides classes for data compression and decompression. For compressing data to a ZIP file ZipOutputStream class can be used. The ZipOutputStream writes data to an output stream in zip format.
Steps to zip a file in Java
- First you need to create a ZipOutputStream object, to which you pass the output stream of the file you wish to use as a zip file.
- Then you also need to create an InputStream for reading the source file.
- Create a ZipEntry for file that is read.
ZipEntry entry = new ZipEntry(FILENAME)
Put the zip entry object using the putNextEntry method of ZipOutputStream - That’s it now you have a connection between your InputStream and OutputStream. Now read data from the source file and write it to the ZIP file.
- Finally close the streams.
Java Program to zip a single file
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFileDemo < static final int BUFFER = 1024; public static void main(String[] args) < zipFile(); >// Method to zip file private static void zipFile() < ZipOutputStream zos = null; BufferedInputStream bis = null; try< // source file String fileName = "G:\\abc.txt"; File file = new File(fileName); FileInputStream fis = new FileInputStream(file); bis = new BufferedInputStream(fis, BUFFER); // Creating ZipOutputStream FileOutputStream fos = new FileOutputStream("G:\\abc.zip"); zos = new ZipOutputStream(fos); // ZipEntry --- Here file name can be created using the source file ZipEntry ze = new ZipEntry(file.getName()); // Putting zipentry in zipoutputstream 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 ioExp)< System.out.println("Error while zipping " + ioExp.getMessage()); >finally < if(zos != null)< try < zos.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> if(bis != null) < try < bis.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > > >
Java Program to zip multiple files
In this Java example multiple files are zipped in Java using ZipOutputStream. Each source file is added as a ZipEntry to the ZipOutputStream.
public class ZipFileDemo < public static void main(String[] args) < try < //Source files String file1 = "G:/abc.txt"; String file2 = "G:/Test/abn.txt"; //Zipped file String zipFilename = "G:/final.zip"; File zipFile = new File(zipFilename); 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); // ZipEntry --- Here file name can be created using the source file 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); >// close entry every time zos.closeEntry(); > finally < try < bis.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > >
Zipping Directory recursively in Java
If you have a folder structure as given below and you want to zip all the files in the parent folder and its sub folders recursively, then you need to go through the list of files and folders and compress them.
- You can use Files.walkFileTree() method (Java 7 onward) which recursively visit all the files in a file tree.
- You can read files in the folder with in the code and add them to a list and then compress the files with in that list.
Zipping Directory recursively in Java Using Files.walkFileTree()
If you are using Java 7 or higher then you can use Path and Files.walkFileTree() method to recursively zip the files. Using Files.walkFileTree() method makes the code shorter and leaves most of the work to API.
You need to implement FileVisitor interface which is one of the argument of the walkFileTree() method, implementation of two of the methods of FileVisitor is required-
preVisitDirectory— For directories you just need to make entry of the directory path.
visitFile— Zip each visited file.
Here try-with-resources in Java 7 is also used for managing resources automatically.
import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFolderSeven < // Source folder which has to be zipped static final String FOLDER = "G:\\files"; public static void main(String[] args) < ZipFolderSeven zs = new ZipFolderSeven(); zs.zippingInSeven(); >private void zippingInSeven()< // try with resources - creating outputstream and ZipOutputSttream try (FileOutputStream fos = new FileOutputStream(FOLDER.concat(".zip")); ZipOutputStream zos = new ZipOutputStream(fos)) < Path sourcePath = Paths.get(FOLDER); // using WalkFileTree to traverse directory Files.walkFileTree(sourcePath, new SimpleFileVisitor() < @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException < // it starts with the source folder so skipping that if(!sourcePath.equals(dir))< //System.out.println("DIR " + dir); zos.putNextEntry(new ZipEntry(sourcePath.relativize(dir).toString() + "/")); zos.closeEntry(); >return FileVisitResult.CONTINUE; > @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException < zos.putNextEntry(new ZipEntry(sourcePath.relativize(file).toString())); Files.copy(file, zos); zos.closeEntry(); return FileVisitResult.CONTINUE; >>); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> >
Java code to zip files recursively using list() method
- list()— Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFolderDemo < static final int BUFFER = 1024; // Source folder which has to be zipped static final String FOLDER = "G:\\files"; ListfileList = new ArrayList(); public static void main(String[] args) < ZipFolderDemo zf = new ZipFolderDemo(); // get list of files ListfileList = zf.getFileList(new File(FOLDER)); //go through the list of files and zip them zf.zipFiles(fileList); > private void zipFiles(List fileList)< try< // Creating ZipOutputStream - Using input name to create output name FileOutputStream fos = new FileOutputStream(FOLDER.concat(".zip")); ZipOutputStream zos = new ZipOutputStream(fos); // looping through all the files for(File file : fileList)< // To handle empty directory if(file.isDirectory())< // ZipEntry --- Here file name can be created using the source file ZipEntry ze = new ZipEntry(getFileName(file.toString())+"/"); // Putting zipentry in zipoutputstream zos.putNextEntry(ze); zos.closeEntry(); >else < FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis, BUFFER); // ZipEntry --- Here file name can be created using the source file ZipEntry ze = new ZipEntry(getFileName(file.toString())); // Putting zipentry in zipoutputstream zos.putNextEntry(ze); byte data[] = new byte[BUFFER]; int count; while((count = bis.read(data, 0, BUFFER)) != -1) < zos.write(data, 0, count); >bis.close(); zos.closeEntry(); > > zos.close(); >catch(IOException ioExp) < System.out.println("Error while zipping " + ioExp.getMessage()); ioExp.printStackTrace(); >> /** * This method will give the list of the files * in folder and subfolders * @param source * @return */ private List getFileList(File source)< if(source.isFile())< fileList.add(source); >else if(source.isDirectory()) < String[] subList = source.list(); // This condition checks for empty directory if(subList.length == 0)< //System.out.println("path -- " + source.getAbsolutePath()); fileList.add(new File(source.getAbsolutePath())); >for(String child : subList) < getFileList(new File(source, child)); >> return fileList; > /** * * @param filePath * @return */ private String getFileName(String filePath) < String name = filePath.substring(FOLDER.length() + 1, filePath.length()); //System.out.println(" name " + name); return name; >>
That’s all for this topic Zipping Files And Folders in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Zipping files using java
Кроме общего функционала для работы с файлами Java предоставляет функциональность для работы с таким видом файлов как zip-архивы. Для этого в пакете java.util.zip определены два класса — ZipInputStream и ZipOutputStream
ZipOutputStream. Запись архивов
Для создания архива используется класс ZipOutputStream. Для создания объекта ZipOutputStream в его конструктор передается поток вывода:
ZipOutputStream(OutputStream out)
Для записи файлов в архив для каждого файла создается объект ZipEntry , в конструктор которого передается имя архивируемого файла. А чтобы добавить каждый объект ZipEntry в архив, применяется метод putNextEntry() .
import java.io.*; import java.util.zip.*; public class Program < public static void main(String[] args) < String filename = "notes.txt"; try(ZipOutputStream zout = new ZipOutputStream(new FileOutputStream("output.zip")); FileInputStream fis= new FileInputStream(filename);) < ZipEntry entry1=new ZipEntry("notes.txt"); zout.putNextEntry(entry1); // считываем содержимое файла в массив byte byte[] buffer = new byte[fis.available()]; fis.read(buffer); // добавляем содержимое к архиву zout.write(buffer); // закрываем текущую запись для новой записи zout.closeEntry(); >catch(Exception ex) < System.out.println(ex.getMessage()); >> >
После добавления объекта ZipEntry в поток нам также надо добавить в него и содержимое файла. Для этого используется метод write, записывающий в поток массив байтов: zout.write(buffer); . В конце надо закрыть ZipEntry с помощью метода closeEntry() . После этого можно добавлять в архив новые файлы — в этом случае все вышеописанные действия для каждого нового файла повторяются.
Чтение архивов. ZipInputStream
Для чтения архивов применяется класс ZipInputStream . В конструкторе он принимает поток, указывающий на zip-архив:
ZipInputStream(InputStream in)
Для считывания файлов из архива ZipInputStream использует метод getNextEntry() , который возвращает объект ZipEntry . Объект ZipEntry представляет отдельную запись в zip-архиве. Например, считаем какой-нибудь архив:
import java.io.*; import java.util.zip.*; public class Program < public static void main(String[] args) < try(ZipInputStream zin = new ZipInputStream(new FileInputStream("output.zip"))) < ZipEntry entry; String name; while((entry=zin.getNextEntry())!=null)< name = entry.getName(); // получим название файла System.out.printf("File name: %s \n", name); // распаковка FileOutputStream fout = new FileOutputStream("new" + name); for (int c = zin.read(); c != -1; c = zin.read()) < fout.write(c); >fout.flush(); zin.closeEntry(); fout.close(); > > catch(Exception ex) < System.out.println(ex.getMessage()); >> >
ZipInputStream в конструкторе получает ссылку на поток ввода. И затем в цикле выводятся все файлы и их размер в байтах, которые находятся в данном архиве.
Затем данные извлекаются из архива и сохраняются в новые файлы, которые находятся в той же папке и которые начинаются с «new».