Read the file directly in the Zip file - Java

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

InputStream in = Main.class.getResourceAsStream("/resouces/zipfile/test.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); 

resources is a package, and zipfile is a zip file.

+4
source share
3 answers

If you can be sure that your zip file will never be packaged in 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 options are:

  • Use ZipInputStream to scan through the zip file once for each record that needs to be downloaded. This can be slow if you have many resources, if you cannot reuse the same ZipInputStream for all of your resources.
  • Do not pack the resources of the attached zip file and simply paste them into the jar of code.
  • Copy the attached zip file to a temporary directory and access it using the ZipFile class.
+14
source

Your current approach will definitely not work. You created an arbitrary access scheme and used it in a class that has no idea what you are trying to do. What you can use ZipInputStream to read the record you are looking for:

 URL zipFileURL = Thread.currentThread().getContextClassLoader().getResource("zipfile.zip"); InputStream inputStream = zipFileURL.openStream(); ZipInputStream zipInputStream = new ZipInputStream(inputStream); ZipEntry zipEntry = null; do { zipEntry = zipInputStream.getNextEntry(); if(zipEntry == null) break; } while(zipEntry != null && (! "textfile".equals(zipEntry.getName())); if(zipEntry != null ) { // do some stuff } 

This is adhoc code, correct it to do what you need. In addition, there may be some more efficient classes for processing Zip files, for example, in the IO Apache Commons library.

+3
source

What is the path to test.txt in the zip file? To read this file you need to use the path in the zip file. Also make sure your zip file is in the classpath. In fact, you can link this in a jar file.

0
source

Source: https://habr.com/ru/post/1446251/


All Articles