2012-05-08 58 views
5

我想用Commons VFS2庫創建一個zip文件。我知道如何在使用file前綴時複製文件,但對於zip文件,寫入和讀取未執行。VFS上的Hello world示例:從零開始創建一個zip文件

fileSystemManager.resolveFile("path comes here") -method當我嘗試路徑時失敗zip:/some/file.zip當file.zip是一個不存在的zip文件。我可以解決現有的文件,但不存在的新文件失敗。

那麼如何創建新的zip文件呢?我不能使用createFile(),因爲它不被支持,我不能在調用這個之前創建FileObject。

正常的方法是用resolveFile創建FileObject,然後調用createFile作爲對象。

回答

5

這個問題的答案我需要的是下面的代碼片段:

// Create access to zip. 
FileSystemManager fsManager = VFS.getManager(); 
FileObject zipFile = fsManager.resolveFile("file:/path/to/the/file.zip"); 
zipFile.createFile(); 
ZipOutputStream zos = new ZipOutputStream(zipFile.getContent().getOutputStream()); 

// add entry/-ies. 
ZipEntry zipEntry = new ZipEntry("name_inside_zip"); 
FileObject entryFile = fsManager.resolveFile("file:/path/to/the/sourcefile.txt"); 
InputStream is = entryFile.getContent().getInputStream(); 

// Write to zip. 
byte[] buf = new byte[1024]; 
zos.putNextEntry(zipEntry); 
for (int readNum; (readNum = is.read(buf)) != -1;) { 
    zos.write(buf, 0, readNum); 
} 

這一點,你需要關閉流後,它的作品!

-1

事實上,它可以從共享-VFS通過以下特發唯一創建zip文件:

 destinationFile = fileSystemManager.resolveFile(zipFileName); 
     // destination is created as a folder, as the inner content of the zip 
     // is, in fact, a "virtual" folder 
     destinationFile.createFolder(); 

     // then add files to that "folder" (which is in fact a file) 

     // and finally close that folder to have a usable zip 
     destinationFile.close(); 

     // Exception handling is left at user discretion 
+0

'org.apache.commons.vfs2.FileSystemException:該文件類型不支持創建文件夾.' –