Append a file into existing ZIP using Java
该Java代码读取输入文件`in.zip`,将其中的`abc.txt`文件内容进行修改(替换字符串并添加当前时间),并将修改后的内容与原ZIP文件的其他内容一起写入输出文件`out.zip`。 2025-2-27 17:15:0 Author: blog.gtiwari333.com(查看原文) 阅读量:13 收藏

The following code reads a input file 'in.zip' appends 'abc.txt' with some String content into it and creates output zip file 'out.zip' using Java.

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.zip.ZipOutputStream;

public class ZipTests {

public static void main(String[] args) throws Exception {
var zipFile = new java.util.zip.ZipFile("in.zip");
final var zos = new ZipOutputStream(new FileOutputStream("out.zip"));
for (var e = zipFile.entries(); e.hasMoreElements(); ) {
var entryIn = e.nextElement();
System.out.println("Processing entry " + entryIn.getName());

//need to set next entry before modifying /adding content
zos.putNextEntry(entryIn);

if (entryIn.getName().equalsIgnoreCase("abc.txt")) {
//modify content and save to output zip stream

String content = isToString(zipFile.getInputStream(entryIn));
content = content.replaceAll("key1=value1", "key1=val2");
content += LocalDateTime.now() + "\r\n";

byte[] buf = content.getBytes();
zos.write(buf, 0, buf.length);
} else {
//copy the content
var inputStream = zipFile.getInputStream(entryIn);
byte[] buf = new byte[9096];
int len;
while ((len = inputStream.read(buf)) > 0) {
zos.write(buf, 0, len);
}

}
zos.closeEntry();
}
zos.close();
}

static String isToString(InputStream stringStream) throws Exception {
var result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int length; (length = stringStream.read(buffer)) != -1; ) {
result.write(buffer, 0, length);
}
return result.toString(StandardCharsets.UTF_8);
}

}


文章来源: http://blog.gtiwari333.com/2025/02/append-file-into-existing-zip-using-java.html
如有侵权请联系:admin#unsafe.sh