Read directly a file within a Zip file - Java

后端 未结 3 1891
一个人的身影
一个人的身影 2020-12-19 12:31

My situation is that I have a zip file that contains some files (txt, png, ...) and I want to read it directly by their names, I have tested the following code but no result

3条回答
  •  失恋的感觉
    2020-12-19 13:10

    If you can be sure that your zip file will never be packed inside another jar, you can use something like:

    URL zipUrl = Main.class.getResource("/resources/zipfile.zip");
    URL entryUrl = new URL("jar:" + zipUrl + "!/test.txt");
    InputStream is = entryUrl.openStream();
    

    Or:

    URL zipUrl = Main.class.getResource("/resources/zipfile.zip");
    File zipFile = new File(zipUrl.toURI());
    ZipFile zip = new ZipFile(zipFile);
    InputStream is = zip.getInputStream(zip.getEntry("test.txt"));
    

    Otherwise, your choices are:

    • Use a ZipInputStream to scan through the zip file once for each entry that you need to load. This may be slow if you have a lot of resources, unless you can reuse the same ZipInputStream for all your resources.
    • Don't pack the resources in a nested zip file, and just inline them in the jar with the code.
    • Copy the nested zip file into a temporary directory, and access it using the ZipFile class.

提交回复
热议问题