目次
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;デスクトップ上にディレクトリを作成し、その中にZIPファイルを解凍する。
/* デスクトップパスの取得 */
Path desktopPath = null;
Path userHomePath = Paths.get(System.getProperty("user.home"));
String desktopPathString;
for (String name : new String[] {"Desktop", "デスクトップ"}) {
desktopPath = userHomePath.resolve(name);
if (Files.isDirectory(desktopPath)) {
desktopPathString = desktopPath.toString();
break;
} else {
desktopPath = null;
}
}
if (desktopPath == null) {
desktopPathString = userHomePath.toString();
}
/* ZIPファイルの解凍 */
String zipPathString = desktopPathString + File.separator + "sample.zip";
File parentDirectory = new File(desktopPathString + 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();
if (!zipEntry.isDirectory()) {
extractZipFile(zipInputStream, entryPathString); // 「ZIPファイルの解凍」メソッドの呼び出し
} 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() + ")");
}
}