我想從一個文件夾中創建一個zip存檔並保留(非空)目錄的條目。如何創建一個zip文件並保留目錄的條目?
在下面的代碼中,當目錄傳遞給AddToZip
時,FileInputStream
將引發FileNotFoundException
。我試圖在實際寫入字節的時候添加一個條件,但是它使整個存檔無效。如何將目錄條目添加到存檔?
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(file); // Throws a FileNotFoundException when directory
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
你見過[this](http://stackoverflow.com/questions/740375/directories-in-a-zip-file-when-using-java-util-zip-zipoutputstream)? – fge
@fge:是的,但只是添加沒有寫入字節的條目似乎使存檔無效 – znat
@fge:畢竟它的工作。我不得不將正斜槓添加到文件路徑 – znat