Charlie

[Java] How to zip multiple file to zip file

N 人看过

Using javax.io example


1. Dependency

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.11.0</version>
</dependency>

2. Exmaple

Java code

public static void zipMultipleFiles() throws IOException {
        File newFile = new File("demo.zip");
        // get demo file list
        List<File> demoByteToFileList = demoFileList();
        FileOutputStream fos = new FileOutputStream(newFile);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        for (File demoFile : demoByteToFileList) {
            FileInputStream fis = new FileInputStream(demoFile);
            ZipEntry zipEntry = new ZipEntry(demoFile.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();
}

public static List<File> demoFileList() throws IOException {
        // demo01
        List<File> files = new ArrayList<File>();
        byte[] bytes = 	Files.readAllBytes(Paths.get("/Users/charlie/Pictures/Temp/demo01.png"));
        File tempFile = new File("demo01.png");
        FileUtils.writeByteArrayToFile(tempFile, bytes);
        System.out.println(tempFile.getAbsolutePath());

        // demo02
        byte[] bytes2 = Files.readAllBytes(Paths.get("/Users/charlie/Pictures/Temp/demo02.png"));
        File tempFile2 = new File("demo02.png");
        FileUtils.writeByteArrayToFile(tempFile2, bytes2);
        System.out.println(tempFile2.getAbsolutePath());

        files.add(tempFile);
        files.add(tempFile2);

        return files;
}

Run console

/Users/charlie/Java/code-java/java-demo/demo01.png
/Users/charlie/Java/code-java/java-demo/demo02.png

Result image

image-20221025110004714


3. Source Code

git clone https://github.com/charliee2000/code-java.git