JavaでZip圧縮します。
ZipEntryとかすぐ忘れてしまうので、備忘録としてメモ。
private void createZip() {
File[] files = {/* 圧縮したいファイル配列 */};
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File("hoge.zip"))));
createZip(zos, files);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(zos);
}
}
private void createZip(ZipOutputStream zos, File[] files) throws IOException {
byte[] buf = new byte[1024];
InputStream is = null;
try {
for (File file : files) {
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
is = new BufferedInputStream(new FileInputStream(file));
int len = 0;
while ((len = is.read(buf)) != -1) {
zos.write(buf, 0, len);
}
}
} finally {
IOUtils.closeQuietly(is);
}
}