Java中使用InputStream讀入Jar/zip內容__Java

來源:互聯網
上載者:User

因為項目需要,要把一個zip/jar檔案讀入到後台伺服器上,前台使用者選擇好zip/jar檔案

以後,upload檔案之後,從JarFile對象中迴圈讀取JarEntry對象,然後根據JarFile的

API使用jarFile.getInputStream(JarEntry jarEntry)來讀取每個JarEntry的內容。

可是最近他們想把檔案讀入變成基於inputstream的直接讀取,從http請求中擷取

inputstream之後可以直接讀入。這樣問題就來,怎麼從流中知道每個JarEntry對象

一番研究之後,有了下面的代碼:

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();}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.