2016-05-16 88 views
-2

我正在嘗試編寫一個程序來解壓縮和重新壓縮文件,而不用寫入Java中的磁盤。到目前爲止,我有,解壓縮並重新壓縮文件而不寫入磁盤 - Java

public void unzipFile(String filePath) { 

    FileInputStream fis = null; 
    ZipInputStream zipIs = null; 
    ZipEntry zEntry = null; 
    try { 
     fis = new FileInputStream(filePath); 
     zipIs = new ZipInputStream(new BufferedInputStream(fis)); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     ZipOutputStream zos = new ZipOutputStream(baos); 
     while ((zEntry = zipIs.getNextEntry()) != null) { 
       zos.putNewEntry(zEntry); 
       zos.write(...); 
       zos.close(); 
} 
     } catch (IOException e){ 
      e.printStackTrace(); 
     } 
    } 
} 

我的問題是我不知道如何編寫到ZipOutputStream的ZipEntry。我收到錯誤,「java.util.zip.ZipException:無效的項目大小(預期125673,但得到0字節)」。任何人都可以將我指向正確的方向嗎?

+3

嗯,首先,不叫'close()方法'內循環。 – Andreas

+0

你是怎麼調用這個方法的? –

+0

''好吧,對於初學者來說,不要在循環中調用close()。「 - 嚴重 –

回答

-2

你只需要將數據從ZipInputStream複製到ZipOutputStream你有zos.write(...)聲明。下面,我已將該副本隔離到名爲copyStream()的幫助程序方法,但如果需要,可以將其內聯。

此外,不要關閉循環內的流。我還更改了代碼以使用try-with-resources,以便更好地管理資源,因此您再也看不到任何close()調用。

這裏是一個正在運行的例子:我的機器上

public static void main(String[] args) throws Exception { 
    String filePath = System.getProperty("java.home") + "/lib/rt.jar"; 
    rezipFile(filePath); 
} 
public static void rezipFile(String filePath) throws IOException { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    try (
     ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(filePath))); 
     ZipOutputStream zos = new ZipOutputStream(baos); 
    ) { 
     for (ZipEntry zEntry; (zEntry = zis.getNextEntry()) != null;) { 
      zos.putNextEntry(zEntry); 
      copyStream(zis, zos); 
     } 
    } 
    System.out.println(baos.size() + " bytes copied"); 
} 
private static void copyStream(InputStream in, OutputStream out) throws IOException { 
    byte[] buf = new byte[4096]; 
    for (int len; (len = in.read(buf)) > 0;) 
     out.write(buf, 0, len); 
} 

輸出:

63275847 bytes copied