Currently, I am working on a project where I need to prompt a download a zip file to the user.

I needed to create a zip file on the fly.

Here is how we can create a zip file in Groovy.

def zipFiles(String inputDir) {
		String zipFileName = "download.zip"
		ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName))
		new File(inputDir).eachFile() { file ->
			zipFile.putNextEntry(new ZipEntry(file.getName()))
			def buffer = new byte[1024]
			file.withInputStream { i ->
				def l = i.read(buffer)
				if (l > 0) {
					zipFile.write(buffer, 0, l)
				}
			}
			zipFile.closeEntry()
		}
		zipFile.close()
	}

ref: http://groovy-almanac.org/create-a-zipfile/

Advertisements