Sunday, 24 April 2016

How to compress and decompress files in ZIP format ?


Compress files in ZIP format
Java comes with "java.util.zip" library to implement the data compression in ZIp format.
  1. Read file with "FileInputStream"
  2. Add the file name to "ZipEntry" and output it to "ZipOutputStream"

byte[] buffer = new byte[1024];
try {
  FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
  ZipOutputStream zos = new ZipOutputStream(fos);
  ZipEntry ze = new ZipEntry("spy.log");
  zos.putNextEntry(ze);

  FileInputStream in = new FileInputStream("C:\\spy.log");

  int len;
  while ((len = in.read(buffer)) > 0) {
    zos.write(buffer, 0, len);
  }

  in.close();
  zos.closeEntry();
  zos.close();
  System.out.println("Finished.");
}catch(IOException ex){
  ex.printStackTrace();

}


Decompress files from a ZIP file
  1. Read ZIP file with "ZipInputStream"
  2. Get the files to "ZipEntry” and output it to "FileOutputStream".

String INPUT_ZIP_FILE = "C:\\MyFile.zip";
String OUTPUT_FOLDER = "C:\\outputzip";
byte[] buffer = new byte[1024];

try {
  // Create output directory is not exists
  File folder = new File(OUTPUT_FOLDER);
  if(!folder.exists()){
   folder.mkdir();
  }

  ZipInputStream zis = 
         new ZipInputStream(new FileInputStream(zipFile));
  ZipEntry ze = zis.getNextEntry();

  while (ze!=null){
    String fileName = ze.getName();
    File newFile = 
           new File(outputFolder + File.separator + fileName);
    System.out.println("file unzip : "+ newFile.getAbsoluteFile());

    // Create all non exists folders; else FileNotFoundException will occur for compressed folder
    new File(newFile.getParent()).mkdirs();
    FileOutputStream fos = new FileOutputStream(newFile);
    int len;
    while ((len = zis.read(buffer)) > 0) {
       fos.write(buffer, 0, len);
    }

    fos.close();
    ze = zis.getNextEntry();
  }

  zis.closeEntry();
  zis.close();
  System.out.println("Finished.");
} catch(IOException ex){
    ex.printStackTrace();

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.