getInputStream for a ZipEntry from ZipInputStream

2020-06-07 03:52发布

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

3条回答
你好瞎i
2楼-- · 2020-06-07 04:30

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.

查看更多
Fickle 薄情
3楼-- · 2020-06-07 04:32

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());
}
查看更多
看我几分像从前
4楼-- · 2020-06-07 04:46

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();
}
查看更多
登录 后发表回答