2013-06-27 94 views
0

我想從一個文件夾中創建一個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(); 

} 
+0

你見過[this](http://stackoverflow.com/questions/740375/directories-in-a-zip-file-when-using-java-util-zip-zipoutputstream)? – fge

+0

@fge:是的,但只是添加沒有寫入字節的條目似乎使存檔無效 – znat

+0

@fge:畢竟它的工作。我不得不將正斜槓添加到文件路徑 – znat

回答

0

我已經寫了一些實用方法使用NIO.2文件API的文件和目錄複製到Zip文件(該庫是開源的):

Maven的:

<dependency> 
    <groupId>org.softsmithy.lib</groupId> 
    <artifactId>softsmithy-lib-core</artifactId> 
    <version>0.3</version> 
</dependency> 

教程:

http://softsmithy.sourceforge.net/lib/current/docs/tutorial/nio-file/index.html#AddZipResourceSample

API:CopyFileVisitor.copy

+0

這裏是另一個可以幫助你的例子。 http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_ZipUtilities_ZipEmptyDirectory –

相關問題