Search code examples
javazipzipinputstream

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?


Solution

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