问题描述
我目前正在尝试使用 ZipOutputStream 创建 zipfile 并将其作为 ByteArrayOutputStream 返回。
但是目前想知道如何为 zip 本身分配文件名。
现在它将始终以我不想要的名称“application.zip”生成。
我尝试使用 FileOutputStream 分配它,但解码后它仍然使用默认命名,所以没有运气。
代码如下:
private static ByteArrayOutputStream convertZipToByte(
final String fname,final String content) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fos = new FileOutputStream("usethisinstead.zip");
baos.writeto(fos);
final ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry(fname);
zos.putNextEntry(entry);
zos.write(content.getBytes());
zos.closeEntry();
return baos;
} catch (IOException ex) {
// throwing error ex here
}
}
解决方法
您应该始终在正确的点关闭流,try-with-resources 会自动处理此问题。
从文件写入中拆分 zip 使逻辑更简单,并重新使用 NIO 调用,如下所示:
private static ByteArrayOutputStream
convertZipToByte(final String fname,final String content,final Path zip)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ZipOutputStream zos = new ZipOutputStream(baos)) {
ZipEntry entry = new ZipEntry(fname);
zos.putNextEntry(entry);
zos.write(content.getBytes());
zos.closeEntry();
}
try(OutputStream fos = Files.newOutputStream(zip)) {
baos.writeTo(fos);
}
return baos;
}
为了调用上面的make文件系统Path
比如with:
convertZipToByte("content.txt","Hello World",Path.of("my.zip"));