2015-05-14 81 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的回答嗎?我沒有足夠的聲望點來做到這一點。 –