import java.io.*;
import java.net.URI;
import java.util.Deque;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zip {
public static void main(String[] args) throws IOException {
zip("C://workspace/jsSpeedTest", "C://workspace/file.zip");
}
public static void zip(String directoryStr, String zipFileStr) throws IOException {
//압축할 폴더
File dir = new File(directoryStr);
//zipFile 경로
File zipFile = new File(zipFileStr);
URI base = directory.toURI();
Deque<File> deque = new LinkedList<File>();
deque.push(directory);
OutputStream out = new FileOutputStream(zipFile);
Closeable res = out;
try {
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!deque.isEmpty()) {
directory = deque.pop();
for (File kid : directory.listFiles()) {
String name = base.relativize(kid.toURI()).getPath();
//폴더면 경로 하나 더 들어가서 압축
if (kid.isDirectory()) {
deque.push(kid);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
} else {
//파일이면 그냥 압축
zout.putNextEntry(new ZipEntry(name));
//private static void copy(File file, OutputStream out) 실행
copy(kid, zout);
zout.closeEntry();
}
}
}
} finally {
res.close();
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0) {
break;
}
out.write(buffer, 0, readCount);
}
}
private static void copy(File file, OutputStream out) throws IOException {
InputStream in = new FileInputStream(file);
try {
//copy(InputStream in, OutputStream out) 실행
copy(in, out);
} finally {
in.close();
}
}
}
댓글