不解压修改压缩文件内容_压缩文件

在java中,可以不解压压缩包就修改压缩包中文件的内容。

/**
* 图片输出使用(现在earlying中模板使用)
*
* @param fileMessage
* @return
* @throws UnsupportedEncodingException
*/
@GetMapping("/downloadApplication")
public String downloadApplication(FileMessage fileMessage) throws Exception {
// 获取HttpServletResponse
HttpServletResponse response =
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
// 下载路径
String downUrl = fileMessage.getFileDownloadUri();
if (downUrl != null) {
// 复制模板文件 生成uuid服务名
UUID uuid = UUID.randomUUID();
String newRarFile = "/home/common_files/" + uuid + ".zip";
// 开始复制
updateZipFile(downUrl, newRarFile, fileMessage.getId());
// 设置文件路径
File file = new File(newRarFile);
if (file.exists()) {
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
return "";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "";
}

public void updateZipFile(String inputName, String outPutName, String id) throws IOException {
ZipFile zipFile = new ZipFile(inputName);
// 复制为新zip
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outPutName));
// 遍历所有文件复制
for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
ZipEntry entryIn = (ZipEntry)e.nextElement();
if (!entryIn.getName().equalsIgnoreCase("myMapApp/config.js")) {
// zos.putNextEntry(entryIn);
zos.putNextEntry(new ZipEntry(entryIn.getName()));
InputStream is = zipFile.getInputStream(entryIn);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
zos.write(buf, 0, (len < buf.length) ? len : buf.length);
}
}
// 当前文件需要复写
else {
zos.putNextEntry(new ZipEntry("myMapApp/config.js"));
InputStream is = zipFile.getInputStream(entryIn);
byte[] buf = new byte[1024 * 5];
int len;
while ((len = (is.read(buf))) > 0) {
String s = new String(buf);
if (s.contains("let appid=")) {
buf = s.replaceAll("let appid=", "let appid=\"" + id + "\"").getBytes();
s = s.replaceAll("let appid=", "let appid=\"" + id + "\"");
}
if (s.contains("let service=")) {
buf = s.replaceAll("let service=", "let service=\"" + instanceId + "\"").getBytes();
}
zos.write(buf, 0, (len < buf.length) ? len : buf.length);
}
}
zos.closeEntry();
}
zos.close();
}

这里有一个问题。

zos.putNextEntry(entryIn); 这行代码会报错 --java.util.zip.ZipException: invalid entry compressed size (expected 1466196 but got 1499165 bytes)
原因是复制过程中 压缩方式不同导致流的字节对应不上 所以需要用以下代码。
zos.putNextEntry(new ZipEntry(entryIn.getName()));