我想用 Commons VFS2 库创建一个 zip 文件。我知道如何在使用 file
前缀时复制文件,但对于 zip
文件,写入和读取未实现。
fileSystemManager.resolveFile("path comes here")
- 当我尝试路径 zip:/some/file.zip
时 file.zip 是非现有的 zip 文件。我可以解析现有文件,但不存在的新文件失败。
那么如何创建新的 zip 文件呢?我无法使用 createFile(),因为它不受支持,而且我无法在调用它之前创建 FileObject。
通常的方法是使用该 resolveFile 创建 FileObject,然后为该对象调用 createFile。
最佳答案
我需要的答案是以下代码片段:
// 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);
}
在此之后您需要关闭流并且它可以工作!
关于java - VFS : create a zip file from scratch 上的 Hello world 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10500494/