英文:
Add JarOutputStream to ZipOutputStream
问题
目前我已经生成了一个JarOutputStream和一个填充有*.java文件的目录。
我想将最终的JarOutputStream添加到一个ZipOutputStream中,以便返回一个包含目录和*.jar文件的最终*.zip文件。
现在我想知道如何以及是否可以将JarOutputStream添加到ZipOutputStream中。
非常感谢!
英文:
currently I have generated a JarOutputStream and a Directory filled with *.java files.
I want to add the final JarOutputStream to a ZipOutputStream to return a final *.zip file with the directory and the *.jar file.
Now I wanted to know, how and if I can add JarOutputStream to a ZipOutputStream.
Thanks alot!
答案1
得分: 1
不过,如果您想要将内容写入一个JAR文件,然后将其写入ZIP文件,而无需在内存中保存所有内容,可以按照以下方式进行:
public static class ExtZipOutputStream extends ZipOutputStream {
public ExtZipOutputStream(OutputStream out) {
super(out);
}
public JarOutputStream putJarFile(String name) throws IOException {
ZipEntry zipEntry = new ZipEntry(name);
putNextEntry(zipEntry);
return new JarOutputStream(this) {
@Override
public void close() throws IOException {
/* 重要:我们完成ZIP输出流的内容写入,但不关闭底层的ExtZipOutputStream */
super.finish();
ExtZipOutputStream.this.closeEntry();
}
};
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
try (ExtZipOutputStream zos = new ExtZipOutputStream(new FileOutputStream("target.zip"))) {
try (JarOutputStream jout = zos.putJarFile("embed.jar")) {
/*
* 在此处添加文件到嵌入的JAR文件中...
*/
}
/*
* 在此处添加其他文件到ZIP文件中...
*/
}
}
英文:
I'm not sure what you actually mean with "I have generated a JarOutputStream". But if you want to write content to a JAR file that is then written to a ZIP file, without the need to hold everything in memory, you could do this the following way:
public static class ExtZipOutputStream extends ZipOutputStream {
public ExtZipOutputStream(OutputStream out) {
super(out);
}
public JarOutputStream putJarFile(String name) throws IOException {
ZipEntry zipEntry = new ZipEntry(name);
putNextEntry(zipEntry);
return new JarOutputStream(this) {
@Override
public void close() throws IOException {
/* IMPORTANT: We finish writing the contents of the ZIP output stream but do
* NOT close the underlying ExtZipOutputStream
*/
super.finish();
ExtZipOutputStream.this.closeEntry();
}
};
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
try (ExtZipOutputStream zos = new ExtZipOutputStream(new FileOutputStream("target.zip"))) {
try (JarOutputStream jout = zos.putJarFile("embed.jar")) {
/*
* Add files to embedded JAR file here ...
*/
}
/*
* Add additional files to ZIP file here ...
*/
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论