我怎样才能从一个ZipInputStream中获取一个ZipEntry的InputStream,而不使用ZipFile类呢?
它的工作方式是这样的
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();
}
ZipInputStream zipInputStream = new ZipInputStream(jar.openStream());
开始,它会如何工作? - David WilliamsErr,ZipInputStream
已经是一个 InputStream
。你不需要另一个。获取下一个 ZipEntry
会将流定位到条目的开头。请参阅Javadoc。
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());
}
ZipFile zipFile = new ZipFile(filePath);
ZipEntry entry = zipFile.getEntry(entryName);
InputStream inputStream = zipFile.getInputStream(entry);
- kirhgoff