Groovy中是否有内置的支持处理Zip文件的方法(使用groovy的方式)?
还是我必须在Groovy中使用Java的java.util.zip.ZipFile来处理Zip文件?
也许 Groovy 没有对 zip 文件的“本地”支持,但是使用它们还是相当容易的。
我正在使用 zip 文件,并且以下是我正在使用的一些逻辑:
def zipFile = new java.util.zip.ZipFile(new File('some.zip'))
zipFile.entries().each {
println zipFile.getInputStream(it).text
}
您可以使用findAll
方法添加其他逻辑:
def zipFile = new java.util.zip.ZipFile(new File('some.zip'))
zipFile.entries().findAll { !it.directory }.each {
println zipFile.getInputStream(it).text
}
根据我的经验,最好的方法是使用Antbuilder:
def ant = new AntBuilder() // create an antbuilder
ant.unzip( src:"your-src.zip",
dest:"your-dest-directory",
overwrite:"false" )
使用这种方式,您不需要自己处理所有复杂的事情——ant会为您处理。显然,如果您需要更细粒度的东西,那么这种方式就行不通了,但对于大多数“只需解压此文件”场景,这种方式非常有效。
要使用antbuilder,只需在类路径中包含ant.jar和ant-launcher.jar即可。
Groovy常用扩展项目为Groovy 2.0及以上版本提供了这个功能:https://github.com/timyates/groovy-common-extensions
import org.apache.commons.io.FileUtils
import java.nio.file.Files
import java.nio.file.Paths
import java.util.zip.ZipFile
def unzipFile(File file) {
cleanupFolder()
def zipFile = new ZipFile(file)
zipFile.entries().each { it ->
def path = Paths.get('c:\\folder\\' + it.name)
if(it.directory){
Files.createDirectories(path)
}
else {
def parentDir = path.getParent()
if (!Files.exists(parentDir)) {
Files.createDirectories(parentDir)
}
Files.copy(zipFile.getInputStream(it), path)
}
}
}
private cleanupFolder() {
FileUtils.deleteDirectory(new File('c:\\folder\\'))
}
本文扩展了AntBuilder示例。
http://preferisco.blogspot.com/2010/06/using-goovy-antbuilder-to-zip-unzip.html
然而,作为一个原则问题 - 是否有一种方法可以找出在研究Groovy/Java中的新方面时可以使用的所有属性、闭包、映射等等呢?似乎有很多非常有用的东西,但如何解锁它们的隐藏宝藏呢?NetBeans/Eclipse代码完成功能现在在这里拥有的新语言丰富性方面似乎已经无望了。
// build.gradle
task doUnTar << {
copy {
// tarTree uses file ext to guess compression, or may be specific
from tarTree(resources.gzip('foo.tar.gz'))
into getBuildDir()
}
}
task doUnZip << {
copy {
from zipTree('bar.zip')
into getBuildDir()
}
}
比如说(这会将 bar.zip
和 foo.tgz
压缩文件解压到目录 build
中):
$ gradle doUnZip
$ gradle doUnTar
def zip(String s){
def targetStream = new ByteArrayOutputStream()
def zipStream = new GZIPOutputStream(targetStream)
zipStream.write(s.getBytes())
zipStream.close()
def zipped = targetStream.toByteArray()
targetStream.close()
return zipped.encodeBase64()
}