Java ZipOutputStream set compress level

Description

Java ZipOutputStream set compress level

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
  public static void main(String[] args) {
    String zipFileName = "Main.zip";
    String[] zipEntries = new String[] {"test1.txt","Main.txt"};

    try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(
        new FileOutputStream(zipFileName)))) {
      zos.setLevel(Deflater.BEST_COMPRESSION);

      for (int i = 0; i < zipEntries.length; i++) {
        File entryFile = new File(zipEntries[i]);
        if (!entryFile.exists()) {
          System.out.println(entryFile.getAbsolutePath()+ " does not exist");
          return;
        }/*from ww  w .  ja  v  a2s.c o  m*/
        ZipEntry ze = new ZipEntry(zipEntries[i]);
        zos.putNextEntry(ze);
        addEntryContent(zos, zipEntries[i]);
        zos.closeEntry();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void addEntryContent(ZipOutputStream zos, String entryFileName)
      throws IOException, FileNotFoundException {
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
        entryFileName));

    byte[] buffer = new byte[1024];
    int count = -1;
    while ((count = bis.read(buffer)) != -1) {
      zos.write(buffer, 0, count);
    }
    bis.close();
  }
}



PreviousNext

Related