zip流文件下載加解壓(JAVA),不產生文件

zip不保存文件的文件下載加解壓(JAVA):

package com.thirteen.commander.test;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Author: rsq0113
 * Date: 2020-12-21 21:28
 * Description:
 **/
public class TestHttpDownload {
   
   
    private final static String URL = "http://61.155.169.167:81/code/201812other/jiaoben7986.zip";

    public static void main(String[] args) throws IOException {
   
   
        Map download = download();
        byte[] bs = (byte[])((Map)((Map) download.get("jiaoben7986/")).get("jiaoben7986/css/")).get("jiaoben7986/css/style.css");
        String s = new String(bs);
        System.out.println(s);
    }

    public static Map download() throws IOException {
   
   
        URL url = new URL(URL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403錯誤
        urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        InputStream inputStream = urlConnection.getInputStream();
        Map map = unZip(inputStream);
        return map;
    }

    private static Map unZip(InputStream in) throws IOException {
   
   
        HashMap<String, byte[]> stringHashMap = new HashMap<String, byte[]>();
        ZipInputStream zipInputStream = new ZipInputStream(in);
        ZipEntry ze = zipInputStream.getNextEntry();
        Map out = out(ze, zipInputStream);
        zipInputStream.close();
        return out;
    }

    private static Map out(ZipEntry ze, ZipInputStream zipInputStream) throws IOException {
   
   
        long size = ze.getSize();
        HashMap<String, Object> stringObjectHashMap = new HashMap<String, Object>();
        String name = ze.getName();
        if (ze.isDirectory()) {
   
   
            stringObjectHashMap.put(name, out(zipInputStream.getNextEntry(), zipInputStream));
        } else {
   
   
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[(int) size];
            int length = -1;
            while ((length = zipInputStream.read(buffer, 0, buffer.length)) > -1) {
   
   
                byteArrayOutputStream.write(buffer, 0, length);
            }
            stringObjectHashMap.put(name, byteArrayOutputStream.toByteArray());

            byteArrayOutputStream.close();
        }
        return stringObjectHashMap;
    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章