简体   繁体   中英

java read zip file without unzipping

I'm curious how this could be possible when I see lots of Geeks suggest to use zip.getInputStream(entry) to read the file content in the zip without unzip it. I try it lots of times, no successd since the bytes read from the fileOutputStream.write(bytes);is zero. must unzip it first and then read the unzip files then you can get the real file contents.

could someone help explain why?

private static final String ZIP_FILE_PATH = "F:/zip-test/test.zip";
private static final String DECOMPRESS_PATH_SUFFIX = "F:/zip-decompress";


@Test
public void readZipInnerFileContent() throws IOException {
    ZipFile zipFile = new ZipFile(ZIP_FILE_PATH);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    Map<String, InputStream> map = MapUtil.newHashMap();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        String name = zipEntry.getName();
        if (zipEntry.isDirectory()) {
            File file = new File(DECOMPRESS_PATH_SUFFIX + File.separator + name);
            file.mkdirs();
            continue;
        }
        InputStream inputStream = zipFile.getInputStream(zipEntry);
        map.put(name, inputStream);
    }

    map.forEach((k, v) -> {
        File file = new File(DECOMPRESS_PATH_SUFFIX + File.separator + k);
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            byte[] bytes = new byte[v.available()];
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

    log.info("read end");
}

I'm not sure why there's so much use of File when your goal is to avoid unzipping, but here's an example that looks for source files which are applications in a jar/zip using your basic code. No unzipping (to disk) occurs:

    public void readZipInnerFileContent() throws IOException {
        ZipFile zipFile = new ZipFile(ZIP_FILE_PATH);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            String name = zipEntry.getName();
            if (!zipEntry.isDirectory() && name.endsWith(".java")) {
                InputStream inputStream = zipFile.getInputStream(zipEntry);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                inputStream.transferTo(out);
                String source = new String(out.toByteArray());
                if (source.contains("main(")) {
                    System.out.printf("Found application class source in %s%n", name);
                }
            }
        }
    }
``

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM