目次
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;デスクトップ上の単一ディレクトリを圧縮し、デスクトップ上にZIPファイルを作成する。
String zipPathString = System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "sample.zip";
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPathString))) {
Path targetPath = Paths.get(System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "sample");
compressDirectory(targetPath, targetPath.getFileName().toString(), zipOutputStream);
} catch (FileNotFoundException e) {
System.out.println("ディレクトリの圧縮中にエラーが発生しました! (" + e.getMessage() + ")");
} catch (IOException e) {
System.out.println("ディレクトリの圧縮中にエラーが発生しました! (" + e.getMessage() + ")");
}ディレクトリの圧縮(ZIP形式)メソッド
void compressDirectory(Path targetPath, String parentDirectoryName, ZipOutputStream zipOutputStream) {
try (DirectoryStream<Path> directoryStreamPath = Files.newDirectoryStream(targetPath)) {
String entryDirectoryName;
ZipEntry zipEntry;
int bytes;
byte[] dataBuffer = new byte[16384];
for (Path path : directoryStreamPath) {
if (Files.isDirectory(path)) {
entryDirectoryName = parentDirectoryName + "/" + path.getFileName().toString() + "/"; // ZIPエントリ名には必ず「/」を使う
zipOutputStream.putNextEntry(new ZipEntry(entryDirectoryName));
zipOutputStream.closeEntry();
compressDirectory(path, parentDirectoryName + "/" + path.getFileName().toString(), zipOutputStream);
} else {
zipEntry = new ZipEntry(parentDirectoryName + "/" + path.getFileName().toString());
zipOutputStream.putNextEntry(zipEntry);
try (InputStream inputStream = Files.newInputStream(path);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
while ((bytes = bufferedInputStream.read(dataBuffer, 0, dataBuffer.length)) != -1) {
zipOutputStream.write(dataBuffer, 0, bytes);
}
}
zipOutputStream.closeEntry();
}
}
} catch (IOException e) {
System.out.println("ディレクトリの圧縮中にエラーが発生しました! (" + e.getMessage() + ")");
}
}