Skip to content

Instantly share code, notes, and snippets.

@kntmr
Created January 31, 2017 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kntmr/39a00e7eee59cd9c440badb8609a8899 to your computer and use it in GitHub Desktop.
Save kntmr/39a00e7eee59cd9c440badb8609a8899 to your computer and use it in GitHub Desktop.
java.util.zip.ZipOutputStream による ZIP アーカイブ 1
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 ZipArchive1 {
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);
writeZipEntry(zos, files.toArray(new File[] {}), dirPath);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
void writeZipEntry(ZipOutputStream zos, File[] files, String dirPath) throws IOException {
InputStream is = null;
byte[] buf = new byte[1024];
try {
for (File file : files) {
String entryPath = file.getAbsolutePath().substring(dirPath.length() + 1);
ZipEntry entry = new ZipEntry(entryPath);
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