|
@@ -317,10 +317,11 @@ public class QrcodeAddServiceImpl implements IQrcodeAddService {
|
|
|
return null;
|
|
return null;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // 使用字节数组输出流,在内存中操作
|
|
|
|
|
- try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
|
|
|
- ZipOutputStream zos = new ZipOutputStream(baos)) {
|
|
|
|
|
|
|
+ // 1. 先在 try-with-resources 外面声明 baos,这样它在 try 结束后依然可用
|
|
|
|
|
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
|
|
|
|
|
|
|
|
+ // 2. 在 try-with-resources 中只管理 zos。当这个代码块结束时,zos 会被自动关闭
|
|
|
|
|
+ try (ZipOutputStream zos = new ZipOutputStream(baos)) {
|
|
|
ZipEntry entry = new ZipEntry(txtFileName);
|
|
ZipEntry entry = new ZipEntry(txtFileName);
|
|
|
zos.putNextEntry(entry);
|
|
zos.putNextEntry(entry);
|
|
|
|
|
|
|
@@ -333,14 +334,20 @@ public class QrcodeAddServiceImpl implements IQrcodeAddService {
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
zos.closeEntry();
|
|
zos.closeEntry();
|
|
|
- // zos关闭时会自动写入baos, 无需flush
|
|
|
|
|
|
|
|
|
|
- // 返回内存中的zip文件内容的字节数组
|
|
|
|
|
- return baos.toByteArray();
|
|
|
|
|
|
|
+ // 关键:这里不要 return!
|
|
|
|
|
+ // 代码块会在这里结束,然后 try-with-resources 会自动调用 zos.close()
|
|
|
|
|
+ // zos.close() 会完成ZIP文件的收尾工作,写入“中央目录”
|
|
|
|
|
+
|
|
|
} catch (Exception e) {
|
|
} catch (Exception e) {
|
|
|
logger.error("在内存中创建zip文件失败", e);
|
|
logger.error("在内存中创建zip文件失败", e);
|
|
|
|
|
+ return null; // 或者向上抛出异常
|
|
|
}
|
|
}
|
|
|
- return null;
|
|
|
|
|
|
|
+
|
|
|
|
|
+ // 3. 在 zos 被完全关闭,ZIP 文件结构完整后,再从 baos 获取最终的字节数组并返回
|
|
|
|
|
+ // ByteArrayOutputStream 的 close() 方法是空操作,所以即使在try块中关闭了baos(如果声明在里面),
|
|
|
|
|
+ // 它的内容依然可以访问。但为了逻辑清晰,像现在这样声明在外面是最好的。
|
|
|
|
|
+ return baos.toByteArray();
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|