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

I would like to create a zip file with the Commons VFS2 library. I know how to copy a file when using the prefix file, but for the zipfiles are not written and read.

fileSystemManager.resolveFile("path comes here")-method does not work when I try to use the path zip:/some/file.zipwhen file.zip is a nonexistent zip file. I can resolve an existing file, but a nonexistent new file fails.

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

The usual way is to create a FileObject with this resolveFile, and then call createFile on the object.

+5
source share
2

:

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

, !

+5

, zip Commons-VFS, 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
-1

All Articles