Sunday, July 29, 2012

Treating an archive like a directory with Java 7

Instead of unpacking and repacking a zip/jar archive in order to manipulate its entries, Java 7 allows us to directly access an archive as if it's a directory.
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.HashMap;

public class ZipDirectory {

    private Path path;
    private FileSystem fs;

    public ZipDirectory(String filePath) {
        this.path = Paths.get(filePath);
        try {
            URI uri = URI.create("jar:file:" + path.toUri().getPath());
            fs = FileSystems.newFileSystem(uri, new HashMap(0));
        } catch (IOException ex) {
            System.err.println("Failed to create: " + ex.getMessage());
        }
    }

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

    public void close() {
        try {
            fs.close();
        } catch (IOException ex) {
            System.err.println("Failed to close: " + ex.getMessage());
        }
    }
}
Which you can use like this:


    ZipDirectory zip = new ZipDirectory("some_directory/file.zip");
    Path copyFrom = Paths.get("file_outside_zip.txt");
    Path copyTo = zip.getPath("/file_inside_zip.txt");

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

    zip.close(); // very important

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thanks a lot for sharing this. It works like a charm

    ReplyDelete