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

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

fileSystemManager.resolveFile(“path来到这里”) – 当我尝试路径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,readNum);
}

在此之后你需要关闭流,它的工作原理!

相关文章

Alt+回车 导入包,自动修正Ctrl+N 查找类Ctrl+Sh...
运行程序出现下面错误:HTTP Status 500 ------------------...
1、建立DM的profile,使用的模版在install_root/profileTempl...
使用dom4j解析XML时,要快速获取某个节点的数据,使用XPath是...
英文操作系统导致 Debug 下的变量查看时显示乱码,可通过改变...
eclipse中javascript报错问题处理:三个地方:<1&...