VFS上的Hello world示例:从头开始创建一个zip文件

时间:2012-05-08 14:22:07

标签: java zip apache-commons-vfs

我想用Commons VFS2库创建一个zip文件。我知道在使用file前缀时如何复制文件但是zip文件没有实现写入和读取。

fileSystemManager.resolveFile("path comes here") - 当file.zip是一个不存在的zip文件时,我尝试路径zip:/some/file.zip时方法失败。我可以解析现有文件但不存在的新文件失败。

那么如何创建新的zip文件呢?我不能使用createFile(),因为它不受支持,我无法在调用它之前创建FileObject。

通常的方法是使用该resolveFile创建FileObject,然后为该对象调用createFile。

2 个答案:

答案 0 :(得分:5)

我需要的答案是以下代码段:

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

在此之后你需要关闭流并且它有效!

答案 1 :(得分:-1)

事实上,可以使用以下idio从Commons-VFS创建唯一的zip文件:

        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