Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
java.util.zip.ZipOutputStream による ZIP アーカイブ 2
package sample;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
public class ZipArchive2 {
void archive(String dirPath) {
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(dirPath + ".zip")));
Collection<File> files = FileUtils.listFiles(new File(dirPath), null, true);
for (File file : files) {
String entryPath = file.getAbsolutePath().substring(dirPath.length() + 1);
ZipEntry entry = new ZipEntry(entryPath);
writeZipEntry(zos, file, entry);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
void writeZipEntry(ZipOutputStream zos, File file, ZipEntry entry) throws IOException {
InputStream is = null;
byte[] buf = new byte[1024];
try {
zos.putNextEntry(entry);
is = new BufferedInputStream(new FileInputStream(file));
int len = 0;
while ((len = is.read(buf)) != -1) {
zos.write(buf, 0, len);
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment