フォルダ内のファイルを圧縮します。
/**
* フォルダ圧縮処理
* @param 圧縮対象フォルダ「C:\work\dir」
* @param 圧縮ファイル名「C:\work\send_20181104150000.zip」
*/
private void dirCompress(String dir, String zipFileName) throws Exception {
// 圧縮ストリームオブジェクトを宣言する。
ZipOutputStream zos = null;
try {
// 圧縮ストリームオブジェクトを生成する。
zos = ZipOutputStream(
new FileOutputStream(
new File(zipFileName)), Charset.forName("MS932"));
// フォルダ内のファイル一覧を取得する。
List<Path> filePahtList = Files.list(Paths.get(dir).collect(Collectors.toList());
// ファイル一覧分繰り返す。
for (Path filePath : filePathList) {
archive(zos, filePath, Paths.get(dir).getFileName().toString() + "\\" + filePath.getFileName().toString());
}
zos.closeEntry();
zos.finish();
} catch (Exception e) {
LOGGER.error("エラー発生");
throw new Exception("エラー発生", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (Exception e) {
LOGGER.error("エラー発生");
throw new Exception("エラー発生", e);
}
}
}
}
* 圧縮処理
* @param zos 圧縮ストリーム
* @param filePath 圧縮対象ファイルパス
* @param fileName 圧縮対象ファイル名
*/
private void archive(ZipOutputStream zos, Path filePath, String fileName) throws Exception {
// 圧縮対象ファイルの読込ストリームを宣言する。
BufferedInputStream bis = null;
try {
// zipエントリを作成する。
zos.putNextEntry(new ZipEntry(fileName));
// ファイルの場合
if (! Files.isDirectory(filePath)) {
// 圧縮対象ファイルを読み込む。
bis = new BufferedInputStream(new FileInputStream(filePath.toString()));
// 圧縮対象ファイルをzipファイルに出力する。
int readSize = 0;
byte[] buffer = new byte[1024];
while ((readSize = bis.read(buffer, 0, buffer.length)) != -1) {
zos.write(buffer, 0, readSize);
}
}
} finally {
if (bis != null) {
bis.close();
}
zos.closeEntry();
}
}