To read a zip/JAR file to the backend server as required by the project, the front-end user selects the zip/JAR file.
Later, after the Upload File, read the jarentry object cyclically from the jarfile object, and then
The API uses jarfile. getinputstream (jarentry) to read the content of each jarentry.
However, recently they want to convert the File Reading to direct reading based on inputstream, which is obtained from the HTTP request.
Inputstream can be read directly. In this case, how can we know each jarentry object from the stream?
After some research, we have the following code:
package com.gloomyfish.image.study;import java.io.BufferedInputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.Iterator;import java.util.jar.JarEntry;import java.util.jar.JarInputStream;import java.util.jar.Manifest;public class JarFileReader {private JarInputStream jarInput;private HashMap<String, ByteArrayOutputStream> entriesStreamMap;public JarFileReader(InputStream in) throws IOException {jarInput = new JarInputStream(in);entriesStreamMap = new HashMap<String, ByteArrayOutputStream>();}public void readEntries() throws IOException {JarEntry entry = jarInput.getNextJarEntry();String manifestEntry = null;while(entry != null) {System.out.println("Entry Name = " + entry.getName());if("jp/co/sony/csl/nielsen/phoenix/objectremoval/Mark.class".equals(entry.getName())) {manifestEntry = entry.getName();copyInputStream(jarInput, entry.getName());}entry = jarInput.getNextJarEntry();}System.out.println("Now!! + get jar entry inputstream again...");InputStream inputStream = getCopy(manifestEntry);System.out.println(inputStream.read());}public void copyInputStream(InputStream in, String entryName) throws IOException {if(!entriesStreamMap.containsKey(entryName)) {ByteArrayOutputStream _copy = new ByteArrayOutputStream();int read = 0;int chunk = 0;byte[] data = new byte[256];while(-1 != (chunk = in.read(data))){read += data.length;_copy.write(data, 0, chunk);}entriesStreamMap.put(entryName, _copy);}}public InputStream getCopy(String entryName) {ByteArrayOutputStream _copy = entriesStreamMap.get(entryName);return (InputStream)new ByteArrayInputStream(_copy.toByteArray());}public static void main(String[] args) {File jarFile = new File("D:\\agriculture\\clickremoval.jar");try {InputStream in = new BufferedInputStream(new FileInputStream(jarFile));JarFileReader reader = new JarFileReader(in);reader.readEntries();} catch (IOException e) {e.printStackTrace();}}}