可能是重复问题:
如何在Java中向Zip文件中添加文件?
使用ZipOutputStream打开文件会覆盖它。是否有方法可以保留该文件并只添加新条目?
可能是重复问题:
如何在Java中向Zip文件中添加文件?
使用ZipOutputStream打开文件会覆盖它。是否有方法可以保留该文件并只添加新条目?
该函数将现有的zip文件重命名为一个临时文件,然后将现有zip文件中的所有条目与新文件一起添加,但排除名称与其中一个新文件相同的zip条目。
public static void addFilesToExistingZip(File zipFile,
File[] files) throws IOException {
// get a temp file
File tempFile = File.createTempFile(zipFile.getName(), null);
// delete it, otherwise you cannot rename your existing zip to it.
tempFile.delete();
boolean renameOk=zipFile.renameTo(tempFile);
if (!renameOk)
{
throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
}
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
String name = entry.getName();
boolean notInFiles = true;
for (File f : files) {
if (f.getName().equals(name)) {
notInFiles = false;
break;
}
}
if (notInFiles) {
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the files
for (int i = 0; i < files.length; i++) {
InputStream in = new FileInputStream(files[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(files[i].getName()));
// 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();
tempFile.delete();
}
zipFile.entries()
获取现有文件中所有ZipEntry
对象的枚举,循环遍历它们并将它们全部添加到ZipOutputStream
中,然后再添加您的新条目。在将未压缩的文件添加到zip文件时,必须确保添加CRC32。请查看此处的示例。 http://jcsnippets.atspace.com/java/input-output/create-zip-file.html
你可以使用Zip4j以简单的方式完成,而无需重写所有内容。
这里展示了如何使用Zip4j将文件添加到现有的zip文件中:http://blog.michalszalkowski.com/java/zip4j-add-file-to-existing-zip-file/
同时,你也可以使用Zip4J的ZipOutputStream和SplitOutputStream一起完成。
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.1</version>
</dependency>
例子:
ZipFile zipFile = new ZipFile(new File("/home/szalek/zip/core1.zip"));
ArrayList filesToAdd = new ArrayList();
filesToAdd.add(new File("/home/szalek/zip/someData.txt"));
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
//password
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
parameters.setPassword("test123!");
//password
zipFile.addFiles(filesToAdd, parameters);