Javaでフォルダ内の全てのファイルを圧縮する方法

ZipOutputStream クラスを使用してディレクトリ内のすべてのファイルを圧縮することができます。例を以下に示します。

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

public class FileCompression {
    public static void main(String[] args) {
        String sourceFolder = "path/to/source/folder";
        String zipFile = "path/to/output/zip/file.zip";

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

            // 压缩文件夹下的所有文件
            File folder = new File(sourceFolder);
            compressFolder(folder, folder.getName(), zos);

            zos.close();
            fos.close();

            System.out.println("文件夹压缩完成。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void compressFolder(File folder, String parentFolder, ZipOutputStream zos) throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                compressFolder(file, parentFolder + "/" + file.getName(), zos);
                continue;
            }

            FileInputStream fis = new FileInputStream(file);
            ZipEntry zipEntry = new ZipEntry(parentFolder + "/" + 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();
        }
    }
}

上記のコードでは、sourceFolder 変数を圧縮したいフォルダのパス、zipFile 変数を圧縮したファイルの出力パスとして設定する必要があります。次に、compressFolder メソッドを呼び出して、指定したフォルダ内のすべてのファイルを再帰的に圧縮します。圧縮ファイルは zipFile パスに保存されます。

以上のコードは、単なる例であり、独自のニーズに合わせて適切に変更とエラー処理が必要になる場合があることに注意してください。

bannerAds