2012-05-08 7 views
5

Me gustaría crear un archivo zip con la biblioteca Commons VFS2. Sé cómo copiar un archivo cuando se usa el prefijo file, pero para zip los archivos de escritura y lectura no están implementados.Hola ejemplo mundial en VFS: crear un archivo zip desde cero

fileSystemManager.resolveFile("path comes here") -metodo falla cuando pruebo la ruta zip:/some/file.zip cuando file.zip es un archivo zip no existente. Puedo resolver un archivo existente pero falla un nuevo archivo no existente.

Entonces, ¿cómo crear ese nuevo archivo comprimido? No puedo usar createFile() porque no es compatible y no puedo crear FileObject antes de que se llame.

La forma normal es crear FileObject con ese resolveFile y luego llamar a createFile para el objeto.

Respuesta

5

La respuesta a mi necesidad es el siguiente fragmento de código:

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

Después de ello, tiene que cerrar las corrientes y funciona!

-1

De hecho, es posible crear archivos zip de forma única a partir Commons-VFS usando la siguiente idio:

 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: Este tipo de archivo no es compatible con la creación de carpetas .' –

Cuestiones relacionadas