您当前的位置:首页 > 计算机 > 编程开发 > Java

教你ZIP文件如何解压读取、压缩下载

时间:06-18来源:作者:点击数:

教你ZIP文件如何解压读取、压缩下载

源码如下:

1.zip文件解压读取

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class FilesUtil {

    /**
     * 根据url获取文件
     * @param url 路径
     * @return 文件流
     */
    public static byte[] getFileStream(String url){
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取文件数据
            byte[] btImg = readInputStream(inStream);//得到文件的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
    
    /**
     * 下载文件到本地
     * @param url 文件全路径+文件名
     * @param localUrl 下载到本地的路径,例:windows:D://、linux:/home/server/img/
     */
    public static String downloadFileToLocal(String url,String localUrl){
        // 将网络文件下载本地
        try{
            byte[] data = FilesUtil.getFileStream(url);
            String substring = url.substring(url.lastIndexOf("/") + 1);
            String name = localUrl + substring;
            //创建一个文件对象
            File file = new File(name);
            //创建输出流
            FileOutputStream outStream = new FileOutputStream(file);
            //写入数据
            outStream.write(data);
            //关闭输出流,释放资源
            outStream.close();
            return name;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解压缩(ZIP)文件
     * @param inputFile
     * @throws Exception
     */
    public static void zipUncompress(String inputFile) throws Exception {
        try{
            File srcFile = new File(inputFile);
            // 判断源文件是否存在
            if (!srcFile.exists()) {
                throw new Exception(srcFile.getPath() + "所指文件不存在");
            }
            String destDirPath = inputFile.replace(".zip", "");
            //创建压缩文件对象
            ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"));
            //开始解压
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    srcFile.mkdirs();
                } else {
                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序,先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 读取本地文件夹中的文件
     * @param inputFile
     * @return
     * @throws Exception
     */
    public static List<MultipartFile> readFiles(String inputFile) {
        List<MultipartFile> multipartFiles = new ArrayList<>();
        File srcFile = new File(inputFile);
        if (srcFile.isDirectory()) {
            File next[] = srcFile.listFiles();
            for (int i = 0; i < next.length; i++) {
                File file = next[i];
                MultipartFile multipartFile = fileToMultipartFile(file);
                multipartFiles.add(multipartFile);
            }
        }
        return multipartFiles;
    }

    /**
     * 文件对象转MultipartFile对象
     * @param file 文件
     * @return MultipartFile对象
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        return new CommonsMultipartFile(fileItem);
    }

    /**
     * 根据File对象创建FileItem对象
     * @param file File
     * @return FileItem对象
     */
    public static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

}

2.压缩下载

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FilesUtil {
    /**
     * 图片打包下载
     */
    public static void downloadPictureList(List<String> urls,HttpServletResponse response) {
        String DOMAIN = "";
        List<String> fileNameList = new ArrayList<>();

        for (int i = 0; i < urls.size(); i++) {
            // 获取文件名
            fileNameList.add(StringUtils.substringAfterLast(urls.get(i), "/"));

            // 拼接完整图片路径
            urls.set(i, DOMAIN + urls.get(i));
        }

        // 获取当前类的所在项目路径
        File directory = new File("");
        String courseFile;

        String srcPath;
        File srcFile = null;

        // 要打包的文件列表
        List<File> fileList = new ArrayList<>();

        ZipOutputStream zos = null;
        OutputStream out = null;
        try {
            courseFile = directory.getCanonicalPath();

            // 下载文件
            for (int i = 0; i < urls.size(); i++) {
                String fileName = "\\" + fileNameList.get(i);
                downloadHttpUrl(urls.get(i), courseFile, fileName);
                srcPath = courseFile + fileName;
                srcFile = new File(srcPath);
                fileList.add(srcFile);
            }

            long start = System.currentTimeMillis();

            response.setContentType("application/x-zip-compressed");
            response.setHeader("Content-disposition", "attachment;filename=" + "testtesttest" + ".zip");
            out = response.getOutputStream();
            zos = new ZipOutputStream(out);
            for (File file : fileList) {
                byte[] buf = new byte[2048];
                zos.putNextEntry(new ZipEntry(file.getName()));
                int len;
                FileInputStream in = new FileInputStream(file);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) + " ms");


            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 删除中间文件
        if (fileList != null) {
            for (File file : fileList) {
                System.out.println(deleteFile(file));
            }
        }
    }

    /**
     * 下载文件---返回下载后的文件存储路径
     *
     * @param url 文件路径
     * @param dir 目标存储目录
     * @param fileName 存储文件名
     * @return
     */
    public static void downloadHttpUrl(String url, String dir, String fileName) throws Exception {
        try {
            URL httpurl = new URL(url);
            File dirfile = new File(dir);
            if (!dirfile.exists()) {
                dirfile.mkdirs();
            }
            FileUtils.copyURLToFile(httpurl, new File(dir+fileName));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();         }
    }

    /**
     * 删除文件
     */
    public static boolean deleteFile(File file) {
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

}
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门