Javaでzipファイルを解凍する

Javaでは、ZipInputStreamとZipOutputStreamクラスを使用して壓縮ファイルを解凍したり圧縮したりできます。

圧縮ファイルを解凍する手順

  1. 圧縮ファイルを解凍するZipInputStreamオブジェクトを作成し、そのコンストラクタに解凍する圧縮ファイルをパラメータとして渡す。
  2. ZipInputStreamオブジェクトのgetNextEntry()メソッドでZipファイル内の各エントリ(ファイルやディレクトリ)を取得する。
  3. 解凍したエントリをBufferedOutputStreamやFileOutputStreamといった出力ストリームを使用して指定した場所に展開します。
  4. 手順2と手順3を、全てのエントリーの解凍が完了するまで繰り返します。
  5. ZipInputStreamオブジェクトを閉じる。

圧縮されたアーカイブの解凍方法を説明する、簡単なコードのサンプルを次に示します。

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipExample {
public static void main(String[] args) {
String zipFilePath = "path/to/your/zipfile.zip";
String unzipFolderPath = "path/to/unzip/folder";
try {
FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
String entryName = zipEntry.getName();
String outputFilePath = unzipFolderPath + File.separator + entryName;
if (!zipEntry.isDirectory()) {
// Create the output file
File outputFile = new File(outputFilePath);
outputFile.getParentFile().mkdirs();
// Write the content of the entry to the output file
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = zis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
} else {
// Create the directory
File directory = new File(outputFilePath);
directory.mkdirs();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
fis.close();
System.out.println("Unzip completed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

ZIPファイルを圧縮する手順は解凍の逆であり、java.util.zip パッケージに含まれるZipOutputStreamクラスを使用して実装できます。

bannerAds