Java memory InputStream extract the zip file format

Java memory InputStream extract the zip file format

premise

zip files exist: D: \ tmp \ mytest.zip.

Code

pom.xml

<!-- 日志 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
</dependency>

File Tools FileUtil.java

package com.ydfind.zip;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Objects;
/**
 * 文件操作工具类
 *
 * @author : ydfind
 * @date : 2019-06-06
 */
@Slf4j
public class FileUtil {

    public static void writeFile(String path, String str) throws IOException {
        try {
            File file = new File(path);
            createFileIfNotExist(file);
            FileOutputStream out = new FileOutputStream(file);
            StringBuffer sb = new StringBuffer();
            sb.append(str + "\r\n");
            out.write(sb.toString().getBytes("utf-8"));
            out.close();
        } catch(IOException ex) {
            throw new IOException("writeFile " + path + " error", ex);
        }
    }

    public static String readFile(String path) throws IOException {
        return readFile(path, "utf-8");
    }

    public static String readFile(String path, String encode) throws IOException {
        StringBuffer sb=new StringBuffer();
        String tempstr=null;
        try {
            File file=new File(path);
            if(!file.exists()) {
                throw new FileNotFoundException();
            }
            FileInputStream fis=new FileInputStream(file);
            BufferedReader br=new BufferedReader(new InputStreamReader(fis, encode));
            while((tempstr=br.readLine())!=null) {
                sb.append(tempstr + "\r\n");
            }
        } catch(IOException ex) {
            throw new IOException("readFile " + path + " error", ex);
        }
        return sb.toString();
    }

    public static void createDirIfNotExist(String path){
        File file = new File(path);
        createDirIfNotExist(file);
    }

    public static void createDirIfNotExist(File file){
        if(!file.exists()){
            file.mkdirs();
        }
    }

    public static void createFileIfNotExist(File file) throws IOException {
        createParentDirIfNotExist(file);
        file.createNewFile();
    }

//    public static void createParentDirIfNotExist(String filename){
//        File file = new File(filename);
//        createParentDirIfNotExist(file);
//    }

    public static void createParentDirIfNotExist(File file){
        createDirIfNotExist(file.getParentFile());
    }

    public static Boolean isDirEnd(String name){
        if(Objects.nonNull(name)){
            if(name.endsWith("/") || name.endsWith("\\")) {
                return true;
            }
        }
        return false;
    }
}

zip decompression tools

Two main views decompression method

package com.ydfind.zip;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * zip解压示例
 *
 * @author : ydfind
 * @date : 2019-06-06
 */
@Slf4j
public class ZipUtil {

    public static void main(String[] args) throws IOException {
        String filename = "D:\\tmp\\mytest.zip";
        String path = "D:\\tmp";
        // 法一:解压文件
        ZipUtil.unZip(filename, path + "\\法1\\");
        // 法二:先读到内存,再统一保存
        InputStream inputStream = new FileInputStream(filename);
        Map<String, String> map = null;
        try {
            map = readZipByInputStream(inputStream);
        }finally {
            try{
                inputStream.close();
            }catch (Exception e){
                log.warn("close FileInputStream exception", e);
            }
        }
        if(map != null) {
            for (String name : map.keySet()) {
                log.info("法二:写入文件 = {}", path + "\\法2\\" + name);
                if(FileUtil.isDirEnd(name)){
                    FileUtil.createDirIfNotExist(path + "\\法2\\" + name);
                }else {
                    FileUtil.writeFile(path + "\\法2\\" + name, map.get(name));
                }
            }
        }
    }

    /**
     * 从zip的inputStream中读出map<文件名,内容>
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static Map<String, String> readZipByInputStream(InputStream inputStream) throws IOException {
        Map<String, String> map = new HashMap<String, String >();
        ZipInputStream zip;
        zip = new ZipInputStream(inputStream);
        ZipEntry zipEntry = null;
        while((zipEntry = zip.getNextEntry()) != null){
            String filename = zipEntry.getName();
            if(zipEntry.isDirectory()){
                if(FileUtil.isDirEnd(filename)) {
                    filename += "\\";
                }
            }
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] byteTemp = new byte[1024];
            int num = -1;
            while((num = zip.read(byteTemp,0,byteTemp.length))>-1){
                byteArrayOutputStream.write(byteTemp,0,num);
            }
            byte[] bytes = byteArrayOutputStream.toByteArray();
            String content = new String(bytes,"UTF-8");
            map.put(filename, content);
        }
        return map;
    }

    public static void unZip(String sourceFilename, String targetDir) throws IOException {
        unZip(new File(sourceFilename), targetDir);
    }

    /**
     * 将sourceFile解压到targetDir
     * @param sourceFile
     * @param targetDir
     * @throws RuntimeException
     */
    public static void unZip(File sourceFile, String targetDir) throws IOException {
        long start = System.currentTimeMillis();
        if (!sourceFile.exists()) {
            throw new FileNotFoundException("cannot find the file = " + sourceFile.getPath());
        }
        ZipFile zipFile = null;
        try{
            zipFile = new ZipFile(sourceFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.isDirectory()) {
                    String dirPath = targetDir + "/" + entry.getName();
                    FileUtil.createDirIfNotExist(dirPath);
                } else {
                    File targetFile = new File(targetDir + "/" + entry.getName());
                    FileUtil.createFileIfNotExist(targetFile);
                    InputStream is = null;
                    FileOutputStream fos = null;
                    try {
                        is = zipFile.getInputStream(entry);
                        fos = new FileOutputStream(targetFile);
                        int len;
                        byte[] buf = new byte[1024];
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                    }finally {
                        try{
                            fos.close();
                        }catch (Exception e){
                            log.warn("close FileOutputStream exception", e);
                        }
                        try{
                            is.close();
                        }catch (Exception e){
                            log.warn("close InputStream exception", e);
                        }
                    }
                }
            }
            log.info("解压完成,耗时:" + (System.currentTimeMillis() - start) +" ms");
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    log.warn("close zipFile exception", e);
                }
            }
        }
    }

}

run

Run ZipUtil main function, as a result, can see two decompression method are equal.

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/sndayYU/article/details/91046569