Java - Zipping existing files [duplicate]

若如初见. 提交于 2019-11-30 22:27:29

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

Here you can get answer for your question: http://truezip.schlichtherle.de/2011/07/26/appending-to-zip-files/

It seems that, according to the epic JDK reference, you could use a while zis.getNextEntry() != null loop to loop through the file (where zis is a ZipInputStream), then use zis.read() to read into an array, which is sent to an ArrayList or similar.

Then, one could use toArray(), "cast" it to a byte array with this method and zos.write() it into the output ZIP file (where zos is a ZipOutputStream), using zos.putNextEntry() to make new entries. (You will need to save the ZipEntry and get its name with ze.getName(), with ze being a ZipEntry.)You should replace T with Byte and byte (use byte everywhere but the for loop body) and may need to modify the casting code to use Byte.byteValue() to convert from Byte (wrapper class) to byte (primitive type), like so:

for(int i = 0; i < objects.length; i++) {
    convertedObjects[i] = (Byte)objects[i].byteValue();
}

Note that this is untested and based on the JDK (entries ZipInputStream, ZipOutputStream, ArrayList, and Byte) and a Google search on array casting.

Sorry if that was a bit dense, and hope this helps!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!