温馨提示×

怎么用java实现压缩文件

小亿
79
2023-10-22 09:11:03
栏目: 编程语言

你可以使用Java的ZipOutputStream类来压缩文件。下面是一个简单的例子:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileExample {

    public static void main(String[] args) {
        String sourcePath = "path/to/source/file";
        String zipFilePath = "path/to/zip/file.zip";

        zipFile(sourcePath, zipFilePath);
    }

    public static void zipFile(String sourcePath, String zipFilePath) {
        try {
            File sourceFile = new File(sourcePath);
            FileOutputStream fos = new FileOutputStream(zipFilePath);
            ZipOutputStream zipOut = new ZipOutputStream(fos);

            addFileToZip(sourceFile, zipOut, "");

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

    public static void addFileToZip(File file, ZipOutputStream zipOut, String parentDir) throws IOException {
        String path = parentDir + file.getName();
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File nestedFile : files) {
                addFileToZip(nestedFile, zipOut, path + "/");
            }
        } else {
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(file);
            zipOut.putNextEntry(new ZipEntry(path));

            int length;
            while ((length = fis.read(buffer)) > 0) {
                zipOut.write(buffer, 0, length);
            }

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

在上述示例中,zipFile()方法接受源文件路径和目标ZIP文件路径。它打开源文件,创建一个ZipOutputStream并将源文件添加到压缩包。

addFileToZip()方法是一个递归方法,它将源文件或目录添加到压缩包中。如果源文件是目录,它将遍历目录中的所有文件并递归调用自身。如果源文件是普通文件,它将读取文件内容并将其写入压缩包中。

请确保将sourcePath替换为要压缩的文件或目录的实际路径,并将zipFilePath替换为要创建的ZIP文件的路径。

0