import java.io.*;
import java.util.zip.*;
public class MyZip {
private void zip(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, inputFile, ""); //第三個參數“”是什麼意思
System.out.println("壓縮中…");
out.close();
}
private void zip(ZipOutputStream out, File f, String base)
throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/")); //以下幾行代碼base是什麼意思
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i]);
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
System.out.println(base);
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
public static void main(String[] temp) {
MyZip book = new MyZip();
try {
book.zip("hello.zip", new File("src"));
System.out.println("壓縮完成");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
base就是個你傳入的路徑,“”就是傳入空內容的路徑, base = base.length() == 0 ? "" : base + "/"; 三目運算符,判斷如果傳入的base內容為空串,base 就等於"/";