Zip File System Provider
Introduction
The zip file system provider introduced in the JDK 7 release is an implementation of a custom file system provider. The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider creates multiple file systems — one file system for each zip or JAR file.
The demo/nio/zipfs/src.zip
file in demo and samples ,which can be downloaded explicitly from Demo and Samples contains the source code for the zip file system provider. It also contains the Demo.java
class that shows how to use the zip file system provider.
Using the Zip File System Provider
You can use the factory methods of the java.nio.file.FileSystems
class to create a new zip file system or to obtain a reference to an existing zip file system. Create a zip file system by specifying the path of the zip or JAR file in one of the following ways:
- By using the JAR URL syntax defined in the
java.net.JarURLConnection
classURI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip"); FileSystem fs = FileSystems.newFileSystem(uri, env);
- By specifying a path and using automatic file type detection
Path zipfile = Paths.get("/codeSamples/zipfs/zipfstest.zip"); FileSystem fs = FileSystems.newFileSystem(zipfile, env, null);
Specify the configuration options for the zip file system in the java.util.Map
object passed to the FileSystems.newFileSystem
method. See the Zip File System Properties topic for information about the provider-specific configuration properties for the zip file system.
Once you have an instance of a zip file system, you can invoke the methods of the java.nio.file.FileSystem
and java.nio.file.Path
classes to perform operations such as copying, moving, and renaming files, as well as modifying file attributes.
The following code sample shows how to create a zip file system and copy a file to the new zip file system.
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 ); } } }