Search code examples
groovyzip

How to zip files in groovy not using ant?


I need to zip files in a directory using groovy -- not using ant though.

I have tried out two versions of a code I found on the net.

1) If I comment out the whole InputStream section then zip file with all files is created. But the files are 0 size.

import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

String zipFileName = "output.zip"  
String inputDir = "c:/temp"

ZipOutputStream output = new ZipOutputStream(new FileOutputStream(zipFileName))

byte[] buf = new byte[1024]

new File(inputDir).eachFile() { file ->  
 println file.name.toString()
 println file.toString()

  output.putNextEntry(new ZipEntry(file.name.toString())) // Create the name of the entry in the ZIP

  InputStream input = file.getInputStream() // Get the data stream to send to the ZIP
  // Stream the document data to the ZIP
  int len;
  while((len = input.read(buf)) > 0){
    output.write(buf, 0, len);
    output.closeEntry(); // End of document in ZIP
  }
}  
output.close(); // End of all documents - ZIP is complete

2) If I tried to use this code then the files in the created zip file got incorrect size. Max size is 1024.

import java.util.zip.ZipOutputStream  
import java.util.zip.ZipEntry  
import java.nio.channels.FileChannel  


String zipFileName = "output.zip"  
String inputDir = "c:/temp"

ZipOutputStream output = new ZipOutputStream(new FileOutputStream(zipFileName))

new File(inputDir).eachFile() { file ->  
  zipFile.putNextEntry(new ZipEntry(file.getName()))  
  def buffer = new byte[1024]  
  file.withInputStream { i ->  
    l = i.read(buffer)  
    // check wether the file is empty  
    if (l > 0) {  
      zipFile.write(buffer, 0, l)  
    }  
  }  
  zipFile.closeEntry()  
}  
zipFile.close()

Solution

  • Not sure if the way to get InputStream was good. I could create one using new FileInputStream(file);

    Improved from first example, uses Java 7

    import java.nio.file.Files
    import java.util.zip.ZipEntry
    import java.util.zip.ZipOutputStream
    
    String zipFileName = "c:/output.zip"
    String inputDir = "c:/temp"
    
    ZipOutputStream output = new ZipOutputStream(new FileOutputStream(zipFileName))
    
    
    new File(inputDir).eachFile() { file ->
        if (!file.isFile()) {
            return
        }
        println file.name.toString()
        println file.toString()
    
        output.putNextEntry(new ZipEntry(file.name.toString())) // Create the name of the entry in the ZIP
    
        InputStream input = new FileInputStream(file);
    
        // Stream the document data to the ZIP
        Files.copy(input, output);
        output.closeEntry(); // End of current document in ZIP
        input.close()
    }
    output.close(); // End of all documents - ZIP is complete