【问题标题】:Assigning zip filename in Java and convert it as ByteArrayOutputStream在 Java 中分配 zip 文件名并将其转换为 ByteArrayOutputStream
【发布时间】:2021-09-18 19:43:49
【问题描述】:

我目前正在尝试使用 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
    }
}

【问题讨论】:

  • 你的代码只是在写一个空文件,把baos.writeTo(fos);移到最后,用try-with-resources关闭所有打开的流。

标签: java zip fileoutputstream zipoutputstream


【解决方案1】:

您应该始终在正确的时间关闭流,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;
}

为了调用上面的文件系统Path,比如:

convertZipToByte("content.txt","Hello World", Path.of("my.zip"));

【讨论】:

  • 问题依然存在。当我对 ByteArray 进行编码并稍后对其进行解码时,zip 将重命名为“application.zip”。我需要确保 zip 文件名保持不变。
  • 由于您的问题代码中未提及 application.zip,因此我建议您使用实际运行的代码的详细信息编辑问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-13
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多