2010-06-15 13 views
13

संभव डुप्लिकेट:
Appending files to a zip file with Javaमैं जावा में किसी मौजूदा ज़िप फ़ाइल में प्रविष्टियां कैसे जोड़ सकता हूं?

एक ZipOutputStream के साथ फाइल खुलने का यह अधिलेखित कर देता है। क्या फ़ाइल रखने और बस नई प्रविष्टियां जोड़ने का कोई तरीका है?

+0

क्या आप हमें दिखा सकते हैं कि आपके पास क्या है? –

+0

ज़िप फ़ाइलों के अंत में एक "केंद्रीय निर्देशिका" है, इसलिए उन्हें जोड़ना सीधा नहीं है। –

उत्तर

4

आप मौजूदा फ़ाइल में सभी ज़िप्पेन्ट्री ऑब्जेक्ट्स की गणना प्राप्त करने के लिए zipFile.entries() का उपयोग कर सकते हैं, उनके माध्यम से लूप कर सकते हैं और उन्हें सभी ZipOutputStream में जोड़ सकते हैं, और फिर अपनी नई प्रविष्टियों को जोड़ सकते हैं।

15

फ़ंक्शन मौजूदा ज़िप फ़ाइल को एक अस्थायी फ़ाइल में नामित करता है और फिर नई फ़ाइलों के साथ मौजूदा ज़िप में सभी प्रविष्टियों को जोड़ता है, जिसमें ज़िप प्रविष्टियों को छोड़कर नई फ़ाइलों में से एक के समान नाम होता है।

public static void addFilesToExistingZip(File zipFile, 
     File[] files) throws IOException { 
     // get a temp file 
    File tempFile = File.createTempFile(zipFile.getName(), null); 
     // delete it, otherwise you cannot rename your existing zip to it. 
    tempFile.delete(); 

    boolean renameOk=zipFile.renameTo(tempFile); 
    if (!renameOk) 
    { 
     throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath()); 
    } 
    byte[] buf = new byte[1024]; 

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); 
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); 

    ZipEntry entry = zin.getNextEntry(); 
    while (entry != null) { 
     String name = entry.getName(); 
     boolean notInFiles = true; 
     for (File f : files) { 
      if (f.getName().equals(name)) { 
       notInFiles = false; 
       break; 
      } 
     } 
     if (notInFiles) { 
      // Add ZIP entry to output stream. 
      out.putNextEntry(new ZipEntry(name)); 
      // Transfer bytes from the ZIP file to the output file 
      int len; 
      while ((len = zin.read(buf)) > 0) { 
       out.write(buf, 0, len); 
      } 
     } 
     entry = zin.getNextEntry(); 
    } 
    // Close the streams   
    zin.close(); 
    // Compress the files 
    for (int i = 0; i < files.length; i++) { 
     InputStream in = new FileInputStream(files[i]); 
     // Add ZIP entry to output stream. 
     out.putNextEntry(new ZipEntry(files[i].getName())); 
     // Transfer bytes from the file to the ZIP file 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 
     // Complete the entry 
     out.closeEntry(); 
     in.close(); 
    } 
    // Complete the ZIP file 
    out.close(); 
    tempFile.delete(); 
} 
1

यहाँ ज़िप अभिलेखागार को संशोधित करने पर जावावर्ल्ड से एक detailed article है।

संबंधित मुद्दे