20
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaでZip圧縮

Posted at

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);
	}
}
20
18
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?