grigory mendel
grigory mendel

Reputation: 121

Efficient way to read a small file from a very large Zip file in Java

I was wondering if there is any efficient way to read a small file from a very large zip. I am not interested in any other file in the zip except a small file called inventory.xml.

To be exact, the zip file resides in artifactory. So I don't want to download entire file into my disk as well. Here is what I have now.

URL url = new URL("artifactory-url");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    int status = con.getResponseCode();
    if (status != 200) {
        System.out.println("Unable to find the artifact : " + url.toString());
        return bugs;
    }
    try (ZipInputStream zipStream = new ZipInputStream(con.getInputStream())) {
        ZipEntry entry;
        while ((entry = zipStream.getNextEntry()) != null) {
            if (entry.getName().contains("inventory.xml")) {
                //do something here
            }

        }
    }

Another query is, If I know the co-ordinates of the file, would it help?

Upvotes: 0

Views: 522

Answers (2)

grigory mendel
grigory mendel

Reputation: 121

As many of you mentioned, the code mentioned in the question itself is probably the most efficient solution. Thank you for the help anyway.

Upvotes: 0

Parsifal
Parsifal

Reputation: 4486

ZIP files store their directory at the end of the file, so if you have some way to randomly access the contents of the file you could do this.

However, that's a big "if": it requires Artifactory to support byte-range GETs, and requires you to re-implement (or find/adapt) the code to read the directory structure and retrieve a file from the middle of the archive.

If you need to do this frequently, a far better solution is to change the process that puts those files in Artifactory in the first place. If it's packaged in a JAR that's produced by Maven or another build tool, then it's a simple matter of extracting the files into their own dependency.

Upvotes: 1

Related Questions