java怎么壓縮文件夾下所有文件

小億
162
2024-03-06 17:32:50
欄目: 編程語言

在Java中可以使用ZipOutputStream類來壓縮文件夾下的所有文件。以下是一個(gè)示例代碼:

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolder {

    public static void main(String[] args) {
        File folderToZip = new File("path/to/folder");
        File zipFile = new File("path/to/output.zip");

        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            zipFolder(folderToZip, folderToZip.getName(), zos);

            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void zipFolder(File folder, String parentFolderName, ZipOutputStream zos) throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                zipFolder(file, parentFolderName + "/" + file.getName(), zos);
            } else {
                FileInputStream fis = new FileInputStream(file);

                ZipEntry zipEntry = new ZipEntry(parentFolderName + "/" + file.getName());
                zos.putNextEntry(zipEntry);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }

                fis.close();
                zos.closeEntry();
            }
        }
    }
}

在上面的示例中,首先需要指定要壓縮的文件夾路徑和輸出的zip文件路徑。然后通過zipFolder方法遞歸地遍歷文件夾下的所有文件,并將它們添加到ZipOutputStream中。最后關(guān)閉流來完成壓縮過程。

0