温馨提示×

java怎么压缩文件夹下所有文件

小亿
91
2024-03-06 17:32:50
栏目: 编程语言

在Java中可以使用ZipOutputStream类来压缩文件夹下的所有文件。以下是一个示例代码:

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中。最后关闭流来完成压缩过程。

0