文件解压缩

package com.gangwantech.web.utils;

import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtils {

    /**
     * zip文件解压
     *
     * @param file
     * @return
     */
    public static MultipartFile unZip(MultipartFile file) throws IOException {
        // 构建解压输入流
        ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream());
        ZipEntry entry = null;
        File distFile = null;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                distFile = new File(entry.getName());
                FileOutputStream fos = new FileOutputStream(distFile);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = zipInputStream.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
            }
        }

        MultipartFile multipartFile = fileTransferMultipartFile(distFile);
        return multipartFile;
    }

    /**
     * file转MultipartFile
     * @return
     */
    public static MultipartFile fileTransferMultipartFile(File distFile) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(distFile);
        MockMultipartFile mockMultipartFile = new MockMultipartFile(distFile.getName(), distFile.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        return mockMultipartFile;
    }
}

你可能感兴趣的:(java,spring,开发语言)