2015-05-14 84 views
1

我想从字节数组写入文件名“内容”到现有的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,但它似乎没有工作...)

谢谢!

+0

因为这应该是在内存中,你有没有考虑使用[memoryfilesystem(https://开头的github .COM /马绍尔/ memoryfilesystem)? – fge

回答

1

请勿使用BufferedWriter来编写二进制内容! A Writer是用来编写文本的内容。

使用,来代替:

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

+0

Downvoter请解释。 – fge

+0

非常感谢!你为我省去了很多时间。最感谢! –

0

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

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

前提是你要有这里命名theByteArray变量是一个片段添加到压缩文件中的条目:

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 
} 
+0

为什么,因为使用Java 7 +,您可以像OP那样访问zip文件作为文件系统,并且我的答案也是这样呢? – fge

+0

呃,我没有意识到这个功能。让我对你的答案赞不绝口,它的确更加优雅;)编辑:upvoting的声望点不足...对不起:( –

+0

有人可以提起@fge的回答吗?我没有足够的声望点来做到这一点。 –