2016-05-16 17 views
-2

Ich versuche, ein Programm zum Entpacken und erneutem Zip-Dateien schreiben, ohne auf Festplatte in Java schreiben. Bisher habe ich,Unzip und Zip-Datei entpacken, ohne auf Festplatte zu schreiben - 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(); 
     } 
    } 
} 

Mein Problem ist, ich weiß nicht, wie die ZipEntry zum ZipOutputStream zu schreiben. Ich erhalte den Fehler "java.util.zip.ZipException: ungültige Eintragsgröße (erwartet 125673, aber 0 Byte erhalten)". Kann mir jemand in die richtige Richtung zeigen?

+3

Nun, für Vorspeisen, nicht nennen 'close()' in der Schleife. – Andreas

+0

Wie rufen Sie diese Methode? –

+0

'" Nun, für den Anfang, rufen Sie nicht nahe() innerhalb der Schleife. "- Ernsthaft –

Antwort

-2

Sie müssen nur die Daten von ZipInputStream in die ZipOutputStream kopieren, wo Sie die zos.write(...) Anweisung haben. Unten habe ich die Kopie auf eine Hilfsmethode namens copyStream() isoliert, aber Sie können es inline, wenn Sie möchten.

Schließen Sie auch nicht den Strom innerhalb der Schleife. Ich habe auch den Code geändert, um try-with-resources für eine bessere Ressourcenverwaltung zu verwenden, so dass Sie keine close() Aufrufe mehr sehen.

Hier ist ein aktuelles Beispiel:

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); 
} 

Ausgang auf meinem Rechner:

63275847 bytes copied