JDK 7リリースで導入されたZipファイル・システム・プロバイダは、カスタム・ファイル・システム・プロバイダの実装です。 Zipファイル・システム・プロバイダは、ZipまたはJARファイルを1つのファイル・システムとして扱い、そのファイルの内容を操作する機能を提供します。 Zipファイル・システム・プロバイダは、複数のファイル・システム(ZipまたはJARファイルごとに1つのファイル・システム)を作成します。
デモおよびサンプル内のdemo/nio/zipfs/src.zipファイル(「Demo and Samples」から明示的にダウンロード可能)には、Zipファイル・システム・プロバイダのソース・コードが含まれています。 また、Zipファイル・システム・プロバイダの使用方法を示すDemo.javaクラスも含まれています。
java.nio.file.FileSystemsクラスのファクトリ・メソッドを使用して、新しいZipファイル・システムを作成したり、既存のZipファイル・システムへの参照を取得したりできます。 Zipファイル・システムを作成するには、次のいずれかの方法でZipまたはJARファイルのパスを指定します。
java.net.JarURLConnectionクラスで定義されているJAR URL構文を使用する
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
FileSystem fs = FileSystems.newFileSystem(uri, env);
Path zipfile = Paths.get("/codeSamples/zipfs/zipfstest.zip");
FileSystem fs = FileSystems.newFileSystem(zipfile.toUri(), env, null);または(あるいは両方)
FileSystem fs = FileSystems.newFileSystem(zipfile, null);
FileSystems.newFileSystemメソッドに渡されるjava.util.Mapオブジェクトに、Zipファイル・システムの構成オプションを指定します。 Zipファイル・システムのプロバイダ固有の構成プロパティについては、「Zipファイル・システムのプロパティ」を参照してください。
Zipファイル・システムのインスタンスを作成したあとは、java.nio.file.FileSystemおよびjava.nio.file.Pathクラスのメソッドを呼び出して、ファイルのコピー、移動、名前変更や、ファイル属性の変更などの操作を実行できます。
次のコード例は、Zipファイル・システムを作成し、その新しいZipファイル・システムにファイルをコピーする方法を示しています。
import java.util.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.*;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.copy( externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}