【问题标题】:Writing a file from byte array into a zip file将字节数组中的文件写入 zip 文件
【发布时间】:2015-05-14 09:49:57
【问题描述】:

我正在尝试将字节数组中的文件名“内容”写入现有的 zip 文件。

到目前为止,我已经设法编写了一个文本文件\将特定文件添加到同一个 zip 中。 我正在尝试做的是同样的事情,只是不是文件,而是代表文件的字节数组。我正在编写这个程序,以便它能够在服务器上运行,所以我无法在某处创建物理文件并将其添加到 zip 中,这一切都必须发生在内存中。

到目前为止,这是我的代码,没有“将字节数组写入文件”部分。

public static void test(File zip, byte[] toAdd) throws IOException {

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    Path path = Paths.get(zip.getPath());
    URI uri = URI.create("jar:" + path.toUri());

    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {

        Path nf = fs.getPath("avlxdoc/content");
         try (BufferedWriter writer = Files.newBufferedWriter(nf, StandardOpenOption.CREATE)) {
             //write file from byte[] to the folder
            }


    }
}

(我尝试使用 BufferedWriter 但它似乎不起作用...)

谢谢!

【问题讨论】:

标签: java zipfile


【解决方案1】:

不要使用BufferedWriter 来编写二进制内容! Writer 用于编写 text 内容。

改用它:

final Path zip = file.toPath();

final Map<String, ?> env = Collections.emptyMap();
final URI uri = URI.create("jar:" + zip.toUri());

try (
    final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
)  {
    Files.write(zipfs.getPath("into/zip"), buf,
        StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}

(注意:APPEND 是这里的猜测;从您的问题来看,如果文件已经存在,您想要追加;默认情况下,内容将被覆盖)

【讨论】:

  • 非常感谢!你为我节省了很多时间来弄清楚这一点。非常感谢!
【解决方案2】:

您应该使用 ZipOutputStream 来访问压缩文件。

ZipOutputStream 让您可以根据需要向存档添加条目,指定条目的名称和内容的字节。

假设您有一个名为 theByteArray 的变量,这里是一个用于向 zip 文件添加条目的 sn-p:

ZipOutputStream zos =  new ZipOutputStream(/* either the destination file stream or a byte array stream */);
/* optional commands to seek the end of the archive */
zos.putNextEntry(new ZipEntry("filename_into_the_archive"));
zos.write(theByteArray);
zos.closeEntry();
try {
    //close and flush the zip
    zos.finish();
    zos.flush();
    zos.close();
}catch(Exception e){
    //handle exceptions
}

【讨论】:

  • 为什么,因为使用 Java 7+,您可以像 OP 和我的回答一样,将 zip 文件作为文件系统访问?
  • 呃,我不知道这个功能。让我为你的答案投票,它确实更优雅;)编辑:投票的声誉点不足......对不起:(
  • 有人可以支持@fge 的答案吗?我没有足够的声望点来做到这一点。
猜你喜欢
  • 1970-01-01
  • 2014-04-10
  • 2019-02-07
  • 1970-01-01
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多