将字节数组中的文件写入 zip 文件

Writing a file from byte array into a zip file

我正在尝试将文件名 "content" 从字节数组写入现有的 zip 文件。

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

到目前为止,这是我的代码,没有 "writing byte array to file" 部分。

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 但它似乎没有用...)

谢谢!

不要用BufferedWriter写二进制内容!做一个Writertext内容

改用它:

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 是这里的猜测;从你的问题来看,如果文件已经存在,你想追加;默认情况下,内容将被覆盖)

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

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

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

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
}