zoukankan      html  css  js  c++  java
  • 利用Java进行zip文件压缩与解压缩

    摘自:

      https://www.cnblogs.com/alphajuns/p/12442315.html

    工具类: 

    package com.alphajuns.util;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    
    import org.apache.tools.zip.ZipEntry;
    import org.apache.tools.zip.ZipFile;
    import org.apache.tools.zip.ZipOutputStream;
    
    /**
     * @ClassName ZipUtil
     * @Description 压缩或解压缩zip:由于直接使用java.util.zip工具包下的类,会出现中文乱码问题,所以使用ant.jar中的org.apache.tools.zip下的工具类
     * @Author AlphaJunS
     * @Date 2020/3/8 11:30
     * @Version 1.0
     */
    public class ZipUtil {
    
        /**
         * @Author AlphaJunS
         * @Date 11:32 2020/3/8
         * @Description
          * @param zip 压缩目的地址
         * @param srcFiles 压缩的源文件
         * @return void
         */
        public static void zipFile( String zip , File[] srcFiles ) {
            try {
                if( zip.endsWith(".zip") || zip.endsWith(".ZIP") ){
                    FileOutputStream fos = new FileOutputStream(new File(zip));
                    ZipOutputStream _zipOut = new ZipOutputStream(fos) ;
                    _zipOut.setEncoding("GBK");
                    for( File _f : srcFiles ){
                        handlerFile(zip , _zipOut , _f , "");
                    }
                    fos.close();
                    _zipOut.close();
                }else{
                    System.out.println("target file[" + zip + "] is not .zip type file");
                }
            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }
        }
    
        /**
         * @Author AlphaJunS
         * @Date 11:33 2020/3/8
         * @Description
         * @param zip 压缩的目的地址
         * @param zipOut
         * @param srcFile 被压缩的文件信息
         * @param path 在zip中的相对路径
         * @return void
         */
        private static void handlerFile(String zip , ZipOutputStream zipOut , File srcFile , String path) throws IOException {
            System.out.println(" begin to compression file[" + srcFile.getName() + "]");
            if( !"".equals(path) && ! path.endsWith(File.separator)){
                path += File.separator ;
            }
            if( ! srcFile.getPath().equals(zip) ){
                if( srcFile.isDirectory() ){
                    File[] _files = srcFile.listFiles() ;
                    if( _files.length == 0 ){
                        zipOut.putNextEntry(new ZipEntry( path + srcFile.getName() + File.separator));
                        zipOut.closeEntry();
                    }else{
                        for( File _f : _files ){
                            handlerFile( zip ,zipOut , _f , path + srcFile.getName() );
                        }
                    }
                }else{
                    InputStream _in = new FileInputStream(srcFile) ;
                    zipOut.putNextEntry(new ZipEntry(path + srcFile.getName()));
                    int len = 0 ;
                    byte[] _byte = new byte[1024];
                    while( (len = _in.read(_byte)) > 0  ){
                        zipOut.write(_byte, 0, len);
                    }
                    _in.close();
                    zipOut.closeEntry();
                }
            }
        }
    
        /**
         * @Author AlphaJunS
         * @Date 11:34 2020/3/8
         * @Description 解压缩ZIP文件,将ZIP文件里的内容解压到targetDIR目录下
          * @param zipPath 待解压缩的ZIP文件名
         * @param descDir 目标目录
         * @return java.util.List<java.io.File>
         */
        public static List<File> unzipFile(String zipPath, String descDir) {
            return unzipFile(new File(zipPath) , descDir) ;
        }
    
        /**
         * @Author AlphaJunS
         * @Date 11:36 2020/3/8
         * @Description 对.zip文件进行解压缩
         * @param zipFile 解压缩文件
         * @param descDir 压缩的目标地址,如:D:\测试 或 /mnt/d/测试
         * @return java.util.List<java.io.File>
         */
        @SuppressWarnings("rawtypes")
        public static List<File> unzipFile(File zipFile, String descDir) {
            List<File> _list = new ArrayList<File>() ;
            try {
                ZipFile _zipFile = new ZipFile(zipFile , "GBK") ;
                for( Enumeration entries = _zipFile.getEntries() ; entries.hasMoreElements() ; ){
                    ZipEntry entry = (ZipEntry)entries.nextElement() ;
                    File _file = new File(descDir + File.separator + entry.getName()) ;
                    if( entry.isDirectory() ){
                        _file.mkdirs() ;
                    }else{
                        File _parent = _file.getParentFile() ;
                        if( !_parent.exists() ){
                            _parent.mkdirs() ;
                        }
                        InputStream _in = _zipFile.getInputStream(entry);
                        OutputStream _out = new FileOutputStream(_file) ;
                        int len = 0 ;
                        byte[] _byte = new byte[1024];
                        while( (len = _in.read(_byte)) > 0){
                            _out.write(_byte, 0, len);
                        }
                        _in.close();
                        _out.flush();
                        _out.close();
                        _list.add(_file) ;
                    }
                }
            } catch (IOException e) {
            }
            return _list ;
        }
    
        /**
         * @Author AlphaJunS
         * @Date 11:36 2020/3/8
         * @Description 对临时生成的文件夹和文件夹下的文件进行删除
         * @param delpath
         * @return void
         */
        public static void deletefile(String delpath) {
            try {
                File file = new File(delpath);
                if (!file.isDirectory()) {
                    file.delete();
                } else if (file.isDirectory()) {
                    String[] fileList = file.list();
                    for (int i = 0; i < fileList.length; i++) {
                        File delfile = new File(delpath + File.separator + fileList[i]);
                        if (!delfile.isDirectory()) {
                            delfile.delete();
                        } else if (delfile.isDirectory()) {
                            deletefile(delpath + File.separator + fileList[i]);
                        }
                    }
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    

    测试类: 

    @Test
        public void testZip() {
            String filePath = "D:\pdfTest\合格压缩文件.zip";
            // 获取原文所在目录
            // 服务器上时,文件路径为“/”,此处测试需要换成filePath中的“\”
            //String oldFilePath = filePath.substring(0, filePath.lastIndexOf("/"));
            String oldFilePath = filePath.substring(0, filePath.lastIndexOf("\"));
            System.out.println("原文件路径:" + oldFilePath);
            // 临时目录,原压缩文件解压目录
            String destDirPath = oldFilePath + "\tmp\";
            System.out.println("临时路径:" + destDirPath);
            // 将原压缩文件解压到临时目录
            ZipUtil.unzipFile(filePath, destDirPath);
    
            // 临时目录文件对象
            File destDir = new File(destDirPath);
            // 获取临时目录下的所有文件
            File[] files = destDir.listFiles();
            // 定义变量,保存校验结果
            List<Integer> list = new ArrayList<>();
            // 遍历文件,进行校验
            for (File file: files) {
                String absolutePath = file.getAbsolutePath();
                System.out.println(absolutePath);
                int i = CheckPdfHelper.checkPdf(absolutePath);
                list.add(i);
                // 压缩包中存在不合格PDF文件时
                if (i != 0) {
                    break;
                }
            }
            // 判断是否包含不合格PDF文件
            if (list.contains(1)) {
                System.out.println("压缩文件中包含不合格PDF文件");
                // 删除解压缩的文件和临时目录
                ZipUtil.deletefile(destDirPath);
                // 不合格时,不生成新的压缩包文件
                return;
            } else {
                System.out.println("压缩文件PDF文件均符合要求");
            }
    
            // 获取原压缩文件后缀
            int pos = filePath.lastIndexOf('.');
            String suffix = filePath.substring(pos + 1);
            // 新生成压缩文件路径
            String newFilePath = filePath.substring(0, pos) + ".PSW." + suffix;
            System.out.println("新的压缩文件路径:" + newFilePath);
    
            // 将检验成功的文件压缩成一个新的压缩包
            ZipUtil.zipFile(newFilePath, files);
            // 删除临时目录
            ZipUtil.deletefile(destDirPath);
        }
    

      maven包:

           <dependencies>
      		<dependency>
    			<groupId>org.apache.ant</groupId>
    			<artifactId>ant</artifactId>
    			<version>1.9.7</version>
    		</dependency>
      	</dependencies>
    

      

      

  • 相关阅读:
    20145215《Java程序设计》第4周学习总结
    20145215《Java程序设计》第3周学习总结
    20145215《Java程序设计》第2周学习总结
    关于开源中国的代码托管
    问卷调查
    2019年12月29日 回怼老王
    cnblogs今天挂了
    感悟别人的感悟——写在2020年前一天
    心情随笔_20191231
    js事件冒泡和捕捉
  • 原文地址:https://www.cnblogs.com/wjqhuaxia/p/14774158.html
Copyright © 2011-2022 走看看