使用ant解压缩任务省略基目录

时间:2013-09-09 12:00:51

标签: ant groovy

我有以下格式的拉链:

/a
  /b
    c.txt

我想将其解压缩到目标文件夹,不包括最顶层的目录(/a

如果我的目标是workspace,那么它的内容将是:

/b
  c.txt

限制:我不提前“知道”最顶层的目录名称

此外,最顶层的dir不等于zip文件名减去“zip”

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

下面给出了一个Utility类,它有一个方法可以用来压缩目录,并带有一个选项来排除Directries。 (我在我的一个项目中使用它并且对我来说工作正常。)

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
    }
}

下面给出了使用该类的示例:它排除了当前目录。

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

希望有所帮助!!!

由于

相关问题