275. Implementing SWS for a zip file system
Using a ZIP file system can also be a common use case for SWS. The following snippet of code creates a ZIP file system via the java.nio.file
API and returns the corresponding path:
private static Path zipFileSystem() throws IOException {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
Path root = Path.of("./zips").toAbsolutePath();
Path zipPath = root.resolve("docs.zip")
.toAbsolutePath().normalize();
FileSystem zipfs = FileSystems.newFileSystem(zipPath, env);
Path externalTxtFile = Paths.get("./docs/books.txt");
Path pathInZipfile = zipfs.getPath("/bookszipped.txt");
// copy a file into the zip file
Files.copy(externalTxtFile, pathInZipfile,
StandardCopyOption.REPLACE_EXISTING);
return zipfs.getPath("/");
}
The result is an archive named docs.zip
with a single file named bookszipped.txt
—...