来自ZipInputStream的ZipEntry的getInputStream(不使用ZipFile类)

时间:2013-01-30 11:50:59

标签: java inputstream zipfile zipinputstream

如何在不使用InputStream课程的情况下从ZipEntry获得ZipInputStream的{​​{1}}?

3 个答案:

答案 0 :(得分:18)

它以这种方式工作

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();
}

答案 1 :(得分:16)

错误,ZipInputStream已经是InputStream.你不需要另一个。在条目开头获取流的下一个ZipEntry位置。见Javadoc。

答案 2 :(得分:1)

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

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());
}