Grails Zipping Files

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

One thought on “Grails Zipping Files

  1. new AntBuilder().zip(
    destfile: “test.zip”, basedir: “stuff”,
    includes: “**/*.txt”,
    excludes: “**/*.doc”
    )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s