与此jar命令等效的Java是什么:
C:\>jar cvf myjar.jar directory
我想以编程方式创建这个jar文件,因为我不能确定jar
命令将位于我可以运行外部进程的系统路径上。
编辑:我想要的只是归档(和压缩)一个目录。不必遵循任何java标准。即:标准拉链很好。
答案 0 :(得分:12)
// 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) {
}
中的答案
答案 1 :(得分:4)
你想要的一切都在java.util.jar包中:
http://java.sun.com/javase/6/docs/api/java/util/jar/package-summary.html