Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hello world example on VFS: create a zip file from scratch

I would like to create a zip file with Commons VFS2 library. I know how to copy a file when using file prefix but for zip files write and read are not implemented.

fileSystemManager.resolveFile("path comes here")-method fails when I try path zip:/some/file.zip when file.zip is an non-existing zip-file. I can resolve an existing file but non-existing new file fails.

So how to create that new zip file then? I cannot use createFile() because it is not supported and I cannot create the FileObject before this is to be called.

The normal way is to create FileObject with that resolveFile and then call createFile for the object.

like image 932
mico Avatar asked May 08 '12 14:05

mico


1 Answers

The answer to my need is the following code snippet:

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

After this you need to close the streams and it works!

like image 186
mico Avatar answered Oct 02 '22 17:10

mico