32

我如何在不使用课程的情况下从 a中获得InputStreama ?ZipEntryZipInputStreamZipFile

4

3 回答 3

21

呃,ZipInputStream已经是InputStream.你不需要另一个了。获取下一个ZipEntry将流定位在条目的开头。请参阅 Javadoc。

于 2013-01-30T11:58:51.047 回答
20

它是这样工作的

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();
}
于 2013-01-30T12:06:45.393 回答
3

要返回以后可以使用的输入流列表,我使用了以下内容

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());
}
于 2017-03-16T13:11:49.357 回答