Accessing the contents of a ZIP file

suggest change

The FileSystem API of Java 7 lets you read and add entries in a ZIP file with the Java NIO file API, in the same way as on any other filesystem.

A FileSystem is a resource that should be closed after use, so use try-with-resources.

Reading from an existing file

Path pathToZip = Paths.get("path/to/file.zip");
try(FileSystem zipFs = FileSystems.newFileSystem(pathToZip, null)) {
  Path root = zipFs.getPath("/");
  ... //access the content of the zip file same as ordinary files
} catch(IOException ex) {
  ex.printStackTrace();
}

Creating a new file

Map<String, String> env = new HashMap<>();  
env.put("create", "true"); //required for creating a new zip file
env.put("encoding", "UTF-8"); //optional: default is UTF-8
URI uri = URI.create("jar:file:/path/to/file.zip");
try (FileSystem zipFs = FileSystems.newFileSystem(uri, env)) {
 Path newFile = zipFs.getPath("/newFile.txt");
 //writing to file
 Files.write(newFile, "Hello world".getBytes());
} catch(IOException ex) {
 ex.printStackTrace();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents