如何用Java创建ZIP文件? [英] How do I create a ZIP file in Java?
本文介绍了如何用Java创建ZIP文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个jar命令的Java等价物是什么:
What is the Java equivalent to this jar command:
C:\>jar cvf myjar.jar directory
我想以编程方式创建这个jar文件,因为我不能确定 jar
命令将位于我可以运行外部进程的系统路径上。
I'd like to create this jar file programmatically as I can't be assured that the jar
command will be on the system path where I could just run the external process.
编辑:我想要的只是归档(和压缩)一个目录。不必遵循任何java标准。即:标准拉链是好的。
Edit: All I want is to archive (and compress) a directory. Doesn't have to follow any java standard. Ie: a standard zip is fine.
推荐答案
// These are the files to include in the ZIP file
String[] source = new String[]{"source1", "source2"};
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// Create the ZIP file
String target = "target.zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));
// Compress the files
for (int i=0; i<source.length; i++) {
FileInputStream in = new FileInputStream(source[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(source[i]));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
} catch (IOException e) {
}
你也可以使用从这篇文章中回答如何使用JarOutputStream创建JAR文件?
You can also use the answer from this post How to use JarOutputStream to create a JAR file?
这篇关于如何用Java创建ZIP文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文