目次
import java.io.BufferedOutputStream;
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.ZipInputStream;デスクトップ上にディレクトリを作成し、その中にZIPファイルを解凍する。
String zipPathString = System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "sample.zip";
File parentDirectory = new File(System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "sample");
parentDirectory.mkdir();
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(new File(zipPathString)))) {
ZipEntry zipEntry = zipInputStream.getNextEntry();
String entryPathString;
File entryDirectory;
while (zipEntry != null) {
entryPathString = parentDirectory.getPath() + File.separator + zipEntry.getName();
System.out.println(entryPathString);
if (!zipEntry.isDirectory()) {
extractZipFile(zipInputStream, entryPathString);
} else {
entryDirectory = new File(entryPathString);
entryDirectory.mkdirs();
}
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
}
} catch (IOException e) {
System.out.println("ZIPファイルの解凍中にエラーが発生しました! (" + e.getMessage() + ")");
}ZIPファイルの解凍メソッド
void extractZipFile(ZipInputStream zipInputStream, String entryPathString) {
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(entryPathString))) {
int bytes;
byte[] dataBuffer = new byte[16384];
while ((bytes = zipInputStream.read(dataBuffer)) != -1) {
bufferedOutputStream.write(dataBuffer, 0, bytes);
}
} catch (IOException e) {
System.out.println("ZIPファイルの解凍中にエラーが発生しました! (" + e.getMessage() + ")");
}
}