How can I get an InputStream
for a ZipEntry
from a ZipInputStream
without using the ZipFile
class?
Asked
Active
Viewed 3.6k times
35

Parker
- 7,244
- 12
- 70
- 92

Mohammad Hassany
- 898
- 1
- 14
- 30
-
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 '16 at 12:28
3 Answers
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();
}

Evgeniy Dorofeev
- 133,369
- 30
- 199
- 275
-
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. – Mohammad Hassany Jan 30 '13 at 12:16
-
1How would it work starting with `ZipInputStream zipInputStream = new ZipInputStream(jar.openStream());`? – David Williams Oct 23 '14 at 04:56
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.

user207421
- 305,947
- 44
- 307
- 483
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());
}

Grant
- 258
- 2
- 8
-
1This loads the entire ZIP file into memory. Not a good idea; not scalable;and not what was asked for. – user207421 Oct 22 '17 at 22:46