Is it possible to create a NEW zip file using the java FileSystem?

后端 未结 1 874
既然无缘
既然无缘 2021-02-20 02:54

I\'ve successfully modified the contents of a (existing) zip file using the FileSystem provided by java 7, but when I tried to create a NEW zip file by this method

相关标签:
1条回答
  • 2021-02-20 03:37

    As described in The Oracle Site:

    public static void createZip(Path zipLocation, Path toBeAdded, String internalPath) throws Throwable {
        Map<String, String> env = new HashMap<String, String>();
        // check if file exists
        env.put("create", String.valueOf(Files.notExists(zipLocation)));
        // use a Zip filesystem URI
        URI fileUri = zipLocation.toUri(); // here
        URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
        System.out.println(zipUri);
        // URI uri = URI.create("jar:file:"+zipLocation); // here creates the
        // zip
        // try with resource
        try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
            // Create internal path in the zipfs
            Path internalTargetPath = zipfs.getPath(internalPath);
            // Create parent directory
            Files.createDirectories(internalTargetPath.getParent());
            // copy a file into the zip file
            Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING);
        }
    }
    
    public static void main(String[] args) throws Throwable {
        Path zipLocation = FileSystems.getDefault().getPath("a.zip").toAbsolutePath();
        Path toBeAdded = FileSystems.getDefault().getPath("a.txt").toAbsolutePath();
        createZip(zipLocation, toBeAdded, "aa/aa.txt");
    }
    
    0 讨论(0)
提交回复
热议问题