Search code examples
javazipnio

Trying to implement a manipulatable zip file system - failing


I need to find a solution to be able to manipulate a zip / jar directly (without unpacking) and without using third-party libraries. However I can't seem to grasp how the FileSystem ties in with Path and URI.

The URI that I'm trying to copy to is
jar:file://E:/Projects/ZipDir/dist/test_folder/test.zip!/test_file.txt

The exception I'm getting is:
FileSystemNotFoundException but that zip file definitely does exist.

Using Java 7, this is what I have so far:

...
ZipDirectory zip = new ZipDirectory("test_folder/test.zip");
Path copyTo = zip.getPath("/test_file.txt");
Path copyFrom = Paths.get("test_file.txt");

Files.copy(copyFrom, copyTo, StandardCopyOption.REPLACE_EXISTING);
...

//

import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.HashMap;

public class ZipDirectory {

    private Path path;
    private FileSystem fileSystem;

    public ZipDirectory(String path){
        this.path = Paths.get(Paths.get(path).toUri());
        create();
    }

    private void create(){
        HashMap<String, String> env = new HashMap<>(); 
        env.put("create", "true");
        try {          
            fileSystem = FileSystems.newFileSystem(path, null);
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }

    public Path getPath(String relativePath){
        return Paths.get(URI.create("jar:file:/" + path.toUri().getPath() + "!" + fileSystem.getPath(relativePath)));
    }

    public Path getRoot(){
        return Paths.get(URI.create(path.toUri().getPath() + "!/"));
    }

    public void close(){
        try {
            fileSystem.close();
        } catch (IOException ex) {
            System.err.println(ex);
        }
        fileSystem = null;
    }
}

Solution

  • I never thought I'd answer my own question, but I've got it working:

    Treating an archive like a directory with Java 7