Adding files to zip in java

How to zip directories programmatically using Java

This article is about how to write a utility class for adding files and directories into a compressed zip archive, using built-in Java API.

The java.util.zip package provides the following classes for adding files and directories into a ZIP archive:

    • ZipOutputStream : this is the main class which can be used for making zip file and adding files and directories (entries) to be compressed in a single archive. Here are some important usages of this class:
      • create a zip via its constructor ZipOutputStream(FileOutputStream)
      • add entries of files and directories via method putNextEntry(ZipEntry)
      • w rite binary data to current entry via method write(byte[] bytes, int offset, int length)
      • close current entry via method closeEntry()
      • save and close the zip file via method close()

      folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext

      In addition, the BufferedInputStream class is used to read content of input file via its method read(byte[]) . While reading file’s content, write the bytes read into the current zip entry via ZipOutputStream ’s write() method.

      Following is source code of ZipUtility.java class:

      import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; 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; /** * This utility compresses a list of files to standard ZIP format file. * It is able to compress all sub files and sub directories, recursively. * @author www.codejava.net * */ public class ZipUtility < /** * A constants for buffer size used to read/write data */ private static final int BUFFER_SIZE = 4096; /** * Compresses a list of files to a destination zip file * @param listFiles A collection of files and directories * @param destZipFile The path of the destination zip file * @throws FileNotFoundException * @throws IOException */ public void zip(ListlistFiles, String destZipFile) throws FileNotFoundException, IOException < ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); for (File file : listFiles) < if (file.isDirectory()) < zipDirectory(file, file.getName(), zos); >else < zipFile(file, zos); >> zos.flush(); zos.close(); > /** * Compresses files represented in an array of paths * @param files a String array containing file paths * @param destZipFile The path of the destination zip file * @throws FileNotFoundException * @throws IOException */ public void zip(String[] files, String destZipFile) throws FileNotFoundException, IOException < ListlistFiles = new ArrayList(); for (int i = 0; i < files.length; i++) < listFiles.add(new File(files[i])); >zip(listFiles, destZipFile); > /** * Adds a directory to the current zip output stream * @param folder the directory to be added * @param parentFolder the path of parent directory * @param zos the current zip output stream * @throws FileNotFoundException * @throws IOException */ private void zipDirectory(File folder, String parentFolder, ZipOutputStream zos) throws FileNotFoundException, IOException < for (File file : folder.listFiles()) < if (file.isDirectory()) < zipDirectory(file, parentFolder + "/" + file.getName(), zos); continue; >zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) < zos.write(bytesIn, 0, read); bytesRead += read; >zos.closeEntry(); > > /** * Adds a file to the current zip output stream * @param file the file to be added * @param zos the current zip output stream * @throws FileNotFoundException * @throws IOException */ private void zipFile(File file, ZipOutputStream zos) throws FileNotFoundException, IOException < zos.putNextEntry(new ZipEntry(file.getName())); BufferedInputStream bis = new BufferedInputStream(new FileInputStream( file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) < zos.write(bytesIn, 0, read); bytesRead += read; >zos.closeEntry(); > >

      The ZipUtility class has two public methods for adding files and directories to a zip archive:

        • zip(List listFiles, String destZipFile): accepts a list of File objects to be added to the destZipFile .
        • zip(String[] files, String destZipFile) : accepts an array of file paths to be added to the destZipFile .

        And source code of a test class, ZipUtilityTest.java :

        /** * A console application that tests the ZipUtility class * @author www.codejava.net * */ public class ZipUtilityTest < public static void main(String[] args) < String[] myFiles = ; String zipFile = "E:/Test/MyPics.zip"; ZipUtility zipUtil = new ZipUtility(); try < zipUtil.zip(myFiles, zipFile); >catch (Exception ex) < // some errors occurred ex.printStackTrace(); >> >

        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.

        Источник

        Adding files to zip in 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».

        Источник

        Add Files to Existing ZIP Archive in Java – Example Program

        In this tutorial, we will see how to add a file to an existing ZIP file, using Java, with an example. We will use Java NIO’s new feature ZIP File System Provider to append files to existing files. ZIP File System Provider is capable of treating a ZIP File as a File System. This would mean adding files to an existing archive would be as straight forward as copying a file from your disk to the file system using methods available in NIO class. Getting curious? Let us take you through a step by step guide on how to do this in Java. The high level steps involved in this example are captured below:

        1.Define ZIP File System Properties

        In order to create new entries to a ZIP file, you have to start by defining a HashMap , and push properties “create” to false (as we are reading an existing ZIP File) and encoding to the encoding used in the ZIP file. Note that the encoding parameter is optional. The Java code to define the HashMap is provided below:

         /* Define ZIP File System Properies in HashMap */ MapString, String> zip_properties = new HashMap>(); /* We want to read an existing ZIP File, so we set this to False */ zip_properties.put("create", "false"); /* Specify the encoding as UTF -8 */ zip_properties.put("encoding", "UTF-8"); 

        2.Access Existing ZIP File

        Next, you need to tell the program, where your ZIP file is located. To do this, you create a URI object in Java which points to the actual file on disk. Later, you will know how to create a ZIP File system using the URI Object and the HashMap. The code segment to define a URI object is shown below:

         /* Specify the path to the ZIP File that you want to read as a File System */ URI zip_disk = URI.create("jar:file:/my_zip_file.zip"); 

        3.Create ZIP File System

        Using the HashMap created in step – 1 and the URI object in step-2, we can create a ZIP File System in Java. Once this is done, adding more files to the ZIP file would be a cakewalk. The Java code to create a ZIP file system is show below:

         try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties))  

        4.Append Files to ZIP Archive

        Once we have created a ZIP File System, it is very easy to add more files to it. A screenshot of our ZIP file before adding new files is shown below:

        To add new files to this archive, you have to create a Path object to the file you want to add and use the copy method in Files class to add the file to the archive. You should also define the path in the ZIP file suitably. Here is a code example

         /* Create a Path in ZIP File */ Path ZipFilePath = zipfs.getPath("TESTER.zip"); /* Path where the file to be added resides */ Path addNewFile = Paths.get("C:/temp/TESTER.zip"); /* Append file to ZIP File */ Files.copy(addNewFile,ZipFilePath); 

        That is it! Three lines and you are done. Output screenshot of the resulting file is shown below: (new entry in ZIP file is marked in RED

        ZIP File with new Entry Added
        ZIP File with new Entry Added

        5.Complete Program – Add Entries to ZIP File in Java

        Putting it all together, the complete Java program that utilizes Zip File System Provider (ZPFS) and NIO to append entries into a ZIP file is shown below:

        import java.util.*; import java.net.URI; import java.nio.file.Path; import java.nio.file.*; public class ZPFSAppend  public static void main(String [] args) throws Exception  /* Define ZIP File System Properies in HashMap */ MapString, String> zip_properties = new HashMap>(); /* We want to read an existing ZIP File, so we set this to False */ zip_properties.put("create", "false"); /* Specify the encoding as UTF -8 */ zip_properties.put("encoding", "UTF-8"); /* Specify the path to the ZIP File that you want to read as a File System */ URI zip_disk = URI.create("jar:file:/my_zip_file.zip"); /* Create ZIP file System */ try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties))  /* Create a Path in ZIP File */ Path ZipFilePath = zipfs.getPath("TESTER.zip"); /* Path where the file to be added resides */ Path addNewFile = Paths.get("C:/temp/TESTER.zip"); /* Append file to ZIP File */ Files.copy(addNewFile,ZipFilePath); > > > 

        You can try adding as many entries you want using this approach. Try this code and if you experience any issues, you can post it in the comments section of this blog.

        Источник

        Читайте также:  Jar file java launcher
Оцените статью