1
我正在閱讀本文,以瞭解如何使用Java壓縮/解壓縮文件。我使用this來指導我,它在壓縮文件夾內的所有文件時效果很好,但是當我用包含更多文件夾的文件夾測試它時,它不起作用,它會拋出以下錯誤:如何使用Java將文件夾及其所有文件和子目錄壓縮/解壓縮?
java.io.FileNotFoundException: assets (Access is denied) //assets is the name of the folder I tried to zip
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at Zip.main(Zip.java:24)
這是我使用的類,你會看到它是相同的代碼示例4:
import java.io.*;
import java.util.zip.*;
public class Zip {
static final int BUFFER = 2048;
public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new
FileOutputStream("H:\\myfigs.zip");
CheckedOutputStream checksum = new
CheckedOutputStream(dest, new Adler32());
ZipOutputStream out = new
ZipOutputStream(new
BufferedOutputStream(checksum));
//out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
// get a list of files from current directory
File f = new File(".");
String files[] = f.list();
for (int i=0; i<files.length; i++) {
System.out.println("Adding: "+files[i]);
FileInputStream fi = new
FileInputStream(files[i]);
origin = new
BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i]);
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
System.out.println("checksum: "+checksum.getChecksum().getValue());
} catch(Exception e) {
e.printStackTrace();
}
}
}
變化應作出什麼使這個代碼:從以前的鏈接Zip.java類代碼可以將文件夾內的文件夾及其所有文件壓縮成zip文件?
的[ZipEntry.isDirectory(http://docs.oracle.com/javase/ 7/docs/api/java/util/zip/ZipEntry.html#isDirectory())states * ...將條目添加到Zip文件時,將目錄條目定義爲名稱以'/'*結尾的條目,您只需要在條目名稱中添加尾部斜線,不需要添加任何內容,只需輸入 – MadProgrammer
非常感謝,這對我幫助很大。 – Uriel
@MadProgrammer提供了一個很好的觀點 - 如果您試圖讓zip歸檔文件重新創建一個空文件夾,則需要插入一個ZipEntry,其文件名以斜槓結尾,並且不要添加內容。 –