如何在groovy中压缩文件而不使用ant?
我需要使用groovy压缩目录中的文件——但不使用ant 我已经试用了我在网上找到的两个版本的代码 1) 如果我注释掉整个InputStream部分,那么将创建包含所有文件的zip文件。但文件大小为0如何在groovy中压缩文件而不使用ant?,groovy,zip,Groovy,Zip,我需要使用groovy压缩目录中的文件——但不使用ant 我已经试用了我在网上找到的两个版本的代码 1) 如果我注释掉整个InputStream部分,那么将创建包含所有文件的zip文件。但文件大小为0 import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream String zipFileName = "output.zip" String inputDir = "c:/temp" ZipOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
String zipFileName = "output.zip"
String inputDir = "c:/temp"
ZipOutputStream output = new ZipOutputStream(new FileOutputStream(zipFileName))
byte[] buf = new byte[1024]
new File(inputDir).eachFile() { file ->
println file.name.toString()
println file.toString()
output.putNextEntry(new ZipEntry(file.name.toString())) // Create the name of the entry in the ZIP
InputStream input = file.getInputStream() // Get the data stream to send to the ZIP
// Stream the document data to the ZIP
int len;
while((len = input.read(buf)) > 0){
output.write(buf, 0, len);
output.closeEntry(); // End of document in ZIP
}
}
output.close(); // End of all documents - ZIP is complete
2) 如果我尝试使用此代码,则创建的zip文件中的文件大小不正确。最大大小为1024
import java.util.zip.ZipOutputStream
import java.util.zip.ZipEntry
import java.nio.channels.FileChannel
String zipFileName = "output.zip"
String inputDir = "c:/temp"
ZipOutputStream output = new ZipOutputStream(new FileOutputStream(zipFileName))
new File(inputDir).eachFile() { file ->
zipFile.putNextEntry(new ZipEntry(file.getName()))
def buffer = new byte[1024]
file.withInputStream { i ->
l = i.read(buffer)
// check wether the file is empty
if (l > 0) {
zipFile.write(buffer, 0, l)
}
}
zipFile.closeEntry()
}
zipFile.close()
不确定获取InputStream的方法是否好。我可以使用新的FileInputStream(文件)创建一个 改进自第一个示例,使用Java7
import java.nio.file.Files
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
String zipFileName = "c:/output.zip"
String inputDir = "c:/temp"
ZipOutputStream output = new ZipOutputStream(new FileOutputStream(zipFileName))
new File(inputDir).eachFile() { file ->
if (!file.isFile()) {
return
}
println file.name.toString()
println file.toString()
output.putNextEntry(new ZipEntry(file.name.toString())) // Create the name of the entry in the ZIP
InputStream input = new FileInputStream(file);
// Stream the document data to the ZIP
Files.copy(input, output);
output.closeEntry(); // End of current document in ZIP
input.close()
}
output.close(); // End of all documents - ZIP is complete
根据您自己的编码,只需省略这一行
output.closeEntry();
@tim_yates:因为我们在产品中使用groovy,我不确定是否需要以某种方式导入/包含ant jar。我想要尽可能通用的解决方案。事实上,我希望有人能指出我的代码出了什么问题。Ant与groovy捆绑在一起,因此您可以使用AntBuildery。您的代码工作顺利。是的,我知道InputStream的实现并不好,我希望有人能纠正它。但主要的想法是创建zip文件:-)