Java - Zipping existing files

Michael 'Maik' Ardan picture Michael 'Maik' Ardan · Jan 16, 2013 · Viewed 13.3k times · Source

Possible Duplicate:
Appending files to a zip file with Java

Hello Java Developers,

Here's the scenario:

Say I have a textfile named sample.txt. What I actually want to do is to put the sample.txt file into a *.zip file named TextFiles.zip.

Here's what I have learned so far.

try{
    File f = new File(compProperty.getZIP_OUTPUT_PATH());
    zipOut = new ZipOutputStream(new FileOutputStream(f));
    ZipEntry zipEntry = new ZipEntry("sample.txt");
    zipOut.putNextEntry(zipEntry);
    zipOut.closeEntry();
    zipOut.close();
    System.out.println("Done");

} catch ( Exception e ){
    // My catch block
}

My code so far creates a *.zip file and insert the sample.txt file.
My question is how would I be able to insert an existing file to the created *.zip file?
If your answer has anything to do with TrueZIP, please post an SSCCE.

I have done the following:

  • Googled
  • Search for existing question. ( Found few. No answer. Some didn't answer my particular question.
  • Read TrueZip. Yet, I couldn't understand a thing. ( Please do understand )

Answer

MadProgrammer picture MadProgrammer · Jan 16, 2013

Using the inbuilt Java API. This will add a file to a Zip File, this will replace any existing Zip files that may exist, creating a new Zip file.

public class TestZip02 {

  public static void main(String[] args) {
    try {
      zip(new File("TextFiles.zip"), new File("sample.txt"));
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  public static void zip(File zip, File file) throws IOException {
    ZipOutputStream zos = null;
    try {
      String name = file.getName();
      zos = new ZipOutputStream(new FileOutputStream(zip));

      ZipEntry entry = new ZipEntry(name);
      zos.putNextEntry(entry);

      FileInputStream fis = null;
      try {
        fis = new FileInputStream(file);
        byte[] byteBuffer = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = fis.read(byteBuffer)) != -1) {
          zos.write(byteBuffer, 0, bytesRead);
        }
        zos.flush();
      } finally {
        try {
          fis.close();
        } catch (Exception e) {
        }
      }
      zos.closeEntry();

      zos.flush();
    } finally {
      try {
        zos.close();
      } catch (Exception e) {
      }
    }
  }
}