Search code examples
javazipapache-commons-vfs

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.


Solution

  • 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!