35

How can I get an InputStream for a ZipEntry from a ZipInputStream without using the ZipFile class?

1
  • What about such answer, isnt it better? ZipFile zipFile = new ZipFile(filePath); ZipEntry entry = zipFile.getEntry(entryName); InputStream inputStream = zipFile.getInputStream(entry);
    – kirhgoff
    Mar 11, 2016 at 12:28

3 Answers 3

22

it works this way

static InputStream getInputStream(File zip, String entry) throws IOException {
    ZipInputStream zin = new ZipInputStream(new FileInputStream(zip));
    for (ZipEntry e; (e = zin.getNextEntry()) != null;) {
        if (e.getName().equals(entry)) {
            return zin;
        }
    }
    throw new EOFException("Cannot find " + entry);
}

public static void main(String[] args) throws Exception {
    InputStream in = getInputStream(new File("f:/1.zip"), "launch4j/LICENSE.txt");
    Scanner sc = new Scanner(in);
    while(sc.hasNextLine()) {
        System.out.println(sc.nextLine());
    }
    in.close();
}
3
  • thanks, but i mean instantiating a new InputStream objects that can be used later or when ever needed, not one by one- entry after entry. Jan 30, 2013 at 12:16
  • 1
    How would it work starting with ZipInputStream zipInputStream = new ZipInputStream(jar.openStream());? Oct 23, 2014 at 4:56
  • What is it?! It always return ZipInputStream zin; object - It's one object for zip archive. And it's the same for all entries :-|
    – Vitaly
    Sep 16, 2023 at 10:25
21

Err, the ZipInputStream already is an InputStream. You don't need another one. Getting the next ZipEntry positions the stream at the beginning of the entry. See the Javadoc.

0
2

To return a List of Input Streams that can be used later I used the following

public static List<InputStream> listResourcesInJar(URL jar) throws IOException{
    ZipInputStream zipInputStream = new ZipInputStream(jar.openStream());
    ZipEntry zipEntry = null;

    List<InputStream> inputStreams = new ArrayList<>();

    while ((zipEntry = zipInputStream.getNextEntry()) != null) {
        String entryName = zipEntry.getName();
        if (entryName.endsWith(".xsd")) {
            inputStreams.add(convertToInputStream(zipInputStream));
        }
    }
    return inputStreams;
}

private static InputStream convertToInputStream(final ZipInputStream inputStreamIn) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(inputStreamIn, out);
    return new ByteArrayInputStream(out.toByteArray());
}
1
  • 1
    This loads the entire ZIP file into memory. Not a good idea; not scalable;and not what was asked for.
    – user207421
    Oct 22, 2017 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.