Ori Dar
Ori Dar

Reputation: 19000

Using ant unzip task omitting base directory

I have a zip in the following format:

/a
  /b
    c.txt

I want to unzip it to a destination folder excluding the topmost dir (/a)

Meaning if my dest dir is workspace it's content will be:

/b
  c.txt

Restriction: I don't "know" the topmost dir name in advance

Also, the topmost dir doesn't equal the zip file name minus "zip"

Upvotes: 0

Views: 614

Answers (2)

Anuj Aneja
Anuj Aneja

Reputation: 1344

Below, given is the Utility class having a method which can be used to zip a directory with a option to exclude the Directries. ( I am using this in one of my project and working fine for me.)

class ZipUtil {

    static Logger log = Logger.getLogger(ZipUtil.class)

    static Boolean zipDirectory(String srcDirPath, OutputStream targetOutputStream, List excludeDirs) {
        Boolean ret = true
        File rootFile = new File(srcDirPath)
        byte[] buf = new byte[1024]
        try {

            ZipOutputStream out = new ZipOutputStream(targetOutputStream)

            File rec = new File(srcDirPath)
            rec.eachFileRecurse {File file ->

                if (file.isFile()) {
                    FileInputStream input = new FileInputStream(file)

                    // Store relative file path in zip file
                    String tmp = file.absolutePath.substring(rootFile.absolutePath.size() + 1)

                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(tmp))

                    // Transfer bytes from the file to the ZIP file
                    int len
                    while ((len = input.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    // Complete the entry
                    out.closeEntry()
                    input.close()
                }
            }

            out.close()
        } catch (Exception e) {
            log.error "Encountered error when zipping file $srcDirPath, error is ${e.message}"
            ret = false
        }
        return ret
    }
}

Example to use the class is given below: which excludes the current directory.

zipFile = new File(zipFilePath)
FileOutputStream fileOutputStream = new FileOutputStream(zipFile)
ZipUtil.zipDirectory(tempFolder.absolutePath, fileOutputStream, ['.'])

Hope that helps!!!

Thanks

Upvotes: 0

Ori Dar
Ori Dar

Reputation: 19000

ant.unzip(src : src, dest: target) {
    cutdirsmapper (dirs:1)
}

Upvotes: 2

Related Questions