Java中如何進(jìn)行文件的壓縮與解壓縮

小樊
81
2024-10-27 07:18:02

在Java中,可以使用java.util.zip包中的類(lèi)進(jìn)行文件的壓縮和解壓縮。以下是一個(gè)簡(jiǎn)單的示例,演示了如何使用這些類(lèi)來(lái)壓縮和解壓縮文件:

壓縮文件

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

public class ZipFileExample {
    public static void main(String[] args) {
        String inputDir = "path/to/input/directory";
        String zipFilePath = "path/to/output.zip";

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
            File dir = new File(inputDir);
            zipDirectory(dir, zos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void zipDirectory(File dir, ZipOutputStream zos) throws IOException {
        if (!dir.isDirectory()) {
            throw new IllegalArgumentException("Input must be a directory");
        }

        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                zipDirectory(file, zos);
            } else {
                try (FileInputStream fis = new FileInputStream(file);
                     ZipEntry ze = new ZipEntry(file.getName())) {
                    zos.putNextEntry(ze);

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

                    zos.closeEntry();
                }
            }
        }
    }
}

解壓縮文件

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

public class UnzipFileExample {
    public static void main(String[] args) {
        String zipFilePath = "path/to/input.zip";
        String outputDir = "path/to/output/directory";

        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                String fileName = ze.getName();
                File newFile = new File(outputDir + File.separator + fileName);

                if (!ze.isDirectory()) {
                    try (FileOutputStream fos = new FileOutputStream(newFile);
                         BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = zis.read(buffer)) > 0) {
                            bos.write(buffer, 0, length);
                        }
                    }
                } else {
                    new File(outputDir + File.separator + fileName).mkdirs();
                }

                ze = zis.getNextEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

請(qǐng)注意,這些示例僅用于演示目的,并且假設(shè)輸入和輸出路徑是正確的。在實(shí)際應(yīng)用中,您可能需要添加額外的錯(cuò)誤處理和驗(yàn)證。

0