5

CommonsVFS2ライブラリを使用してzipファイルを作成したいと思います。fileプレフィックスを使用するときにファイルをコピーする方法を知っていますが、zipファイルの書き込みと読み取りは実装されていません。

fileSystemManager.resolveFile("path comes here")zip:/some/file.zip-file.zipが存在しないzipファイルであるときにパスを試行すると、メソッドが失敗します。既存のファイルを解決できますが、存在しない新しいファイルは失敗します。

では、その新しいzipファイルを作成するにはどうすればよいでしょうか。createFile()はサポートされておらず、呼び出される前にFileObjectを作成できないため、使用できません。

通常の方法は、そのresolveFileを使用してFileObjectを作成してから、オブジェクトに対してcreateFileを呼び出すことです。

4

2 に答える 2

6

私の必要性に対する答えは、次のコード スニペットです。

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

この後、ストリームを閉じる必要があり、動作します!

于 2012-05-09T15:27:35.020 に答える
-1

実際、次のイディオを使用して、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
于 2014-05-15T15:42:42.570 に答える