java gzip如何壓縮文件夾

小億
82
2024-09-26 03:33:06

在Java中,你可以使用java.util.zip包中的類(lèi)來(lái)壓縮文件夾。以下是一個(gè)示例代碼,展示了如何壓縮一個(gè)文件夾:

import java.io.*;
import java.nio.file.*;
import java.util.zip.*;

public class FolderGzip {
    public static void main(String[] args) {
        String folderToZip = "/path/to/folder";
        String zipFilePath = "/path/to/output.zip";

        try {
            compressFolder(folderToZip, zipFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void compressFolder(String folderPath, String zipFilePath) throws IOException {
        // 創(chuàng)建一個(gè)文件輸出流,寫(xiě)入ZIP文件
        FileOutputStream fos = new FileOutputStream(zipFilePath);

        // 創(chuàng)建一個(gè)ZIP輸出流,寫(xiě)入到文件輸出流中
        ZipOutputStream zos = new ZipOutputStream(fos);

        // 獲取文件夾中的所有文件和子文件夾
        Path rootPath = Paths.get(folderPath);
        Files.walk(rootPath)
             .filter(path -> !Files.isDirectory(path))
             .forEach(path -> {
                 try {
                     // 創(chuàng)建一個(gè)ZIP條目,使用相對(duì)路徑
                     ZipEntry zipEntry = new ZipEntry(rootPath.relativize(path).toString());
                     zos.putNextEntry(zipEntry);

                     // 讀取文件內(nèi)容并將其寫(xiě)入ZIP輸出流
                     try (InputStream fis = Files.newInputStream(path)) {
                         byte[] buffer = new byte[1024];
                         int bytesRead;
                         while ((bytesRead = fis.read(buffer)) != -1) {
                             zos.write(buffer, 0, bytesRead);
                         }
                     }

                     // 關(guān)閉ZIP條目,完成對(duì)該文件的壓縮
                     zos.closeEntry();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             });

        // 關(guān)閉ZIP輸出流和文件輸出流
        zos.close();
        fos.close();
    }
}

在這個(gè)示例中,compressFolder方法接受要壓縮的文件夾路徑和輸出的ZIP文件路徑。它使用java.nio.file.Files.walk方法遍歷文件夾中的所有文件和子文件夾,并使用java.util.zip.ZipOutputStream將它們添加到ZIP文件中。

0