2012-11-05 19 views
1

我使用非常標準的代碼創建了一個帶有ZipOutputStream的zip文件。由於某種原因,當我將其作爲ZipInputStream讀回來時,ZipEntrysize=-1。文件名正確存儲在ZipEntry中。 (當我使用我的操作系統工具製作一個zip文件,然後再讀回來,大小是正確的,所以我假設問題與ZipOutputStream而不是ZipInputStream)。ZipOutputStream離開大小= -1

上下文是一個Spring MVC控制器。

我在做什麼錯? 謝謝。

下面是代碼:

// export zip file 
String file = "/Users/me/Desktop/test.jpg"; 
FileInputStream fis = new FileInputStream(file); 
FileOutputStream fos = new FileOutputStream(file+".zip"); 
ZipOutputStream zos = new ZipOutputStream(fos); 
zos.putNextEntry(new ZipEntry("test.jpg")); 
byte[] buffer = new byte[1024]; 
int bytesRead; 
while ((bytesRead = fis.read(buffer)) > 0) { 
    zos.write(buffer, 0, bytesRead); 
} 
zos.closeEntry(); 
zos.close(); 
fis.close(); 

// import same file 
String file2 = "/Users/me/Desktop/test.jpg.zip"; 
FileInputStream fis2 = new FileInputStream(file2); 
ZipInputStream zis = new ZipInputStream(fis2); 
ZipEntry entry = zis.getNextEntry(); 
// here: entry.getSize() = -1, zip.buf is an array of zeros... 
// but if I unzip the file on my OS I see that the original file has been zipped... 
+0

你是否在壓縮zip文件? 'ZipEntry entry = new ZipEntry(filename +「。zip」);' – jlordo

+0

順便說一句,一個好主意。雙拉鍊? =) – user

+0

其實沒有。即使使用不同的擴展名,問題仍然存在 – bz3x

回答

1

你必須得到來自流的下一個條目,就像這個例子:

http://www.roseindia.net/tutorial/java/corejava/zip/zipentry.html

當你手動設置大小,它肯定會給你一個結果,就像你已經顯示「64527」一樣。 你最好看看zip示例。他們會給你一個清晰的形象。 另外:Create Java-Zip-Archive from existing OutputStream

試一下,像這樣的:

 String inputFileName = "test.txt"; 
     String zipFileName = "compressed.zip"; 

     //Create input and output streams 
     FileInputStream inStream = new FileInputStream(inputFileName); 
     ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName)); 

     // Add a zip entry to the output stream 
     outStream.putNextEntry(new ZipEntry(inputFileName)); 

     byte[] buffer = new byte[1024]; 
     int bytesRead; 

     //Each chunk of data read from the input stream 
     //is written to the output stream 
     while ((bytesRead = inStream.read(buffer)) > 0) { 
      outStream.write(buffer, 0, bytesRead); 
     } 

     //Close zip entry and file streams 
     outStream.closeEntry(); 

     outStream.close(); 
     inStream.close(); 
+0

我已經有 zos.putNextEntry(entry);代碼中的 。你是說我在某個地方需要它嗎? – bz3x

+0

不是。這只是你需要的一些不同的代碼。在編輯中查找。 – user

+0

謝謝,我已將其修改爲以下內容。 (數據不是來自物理文件,而是來自一個字節[])。代碼' ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); zos.putNextEntry(new ZipEntry(filename +「。foo」)); zos.write(myBytes); //在這裏調試:zos.current.entry.name正確,但大小= -1。 myBytes.length然而是64527! zos.closeEntry(); zos.close(); – bz3x