2012-05-08 33 views
5

Tôi muốn tạo tệp nén bằng thư viện Commons VFS2. Tôi biết cách sao chép tệp khi sử dụng tiền tố file nhưng đối với zip, việc ghi và đọc không được triển khai.Xin chào ví dụ thế giới về VFS: tạo một tệp zip từ đầu

fileSystemManager.resolveFile("path comes here") -method không thành công khi tôi thử đường dẫn zip:/some/file.zip khi tệp.zip là tệp zip không tồn tại. Tôi có thể giải quyết một tập tin hiện có nhưng không tồn tại tập tin mới không thành công.

Vậy làm cách nào để tạo tệp zip mới? Tôi không thể sử dụng createFile() vì nó không được hỗ trợ và tôi không thể tạo FileObject trước khi nó được gọi.

Cách thông thường là tạo FileObject với resolFile đó rồi gọi createFile cho đối tượng.

Trả lời

5

Câu trả lời cho nhu cầu của tôi là đoạn mã sau:

// 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); 
} 

Sau này, bạn cần phải đóng những con suối và nó hoạt động!

-1

Trong thực tế, nó có thể tạo ra các file zip duy nhất từ ​​Commons-VFS bằng idio sau:

 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: loại tập tin này không hỗ trợ tạo thư mục .' –

Các vấn đề liên quan