`

文件压缩整理 File-ZIP

    博客分类:
  • JAVA
阅读更多

示例代码:

 

String zipFilePath = filePath+".zip";   //压缩文件 在原文件名的基础上,追加 。zip
ZipUtil.compress(filePath,zipFilePath);	//压缩文件

  

 

/** 
  * @Description:  
  *     压缩和解压工具 
 */  
public class ZipUtil {  
 
   public static void compress(String srcFilePath, String destFilePath) { 
        File srcFile = new File(srcFilePath); 
        if (!srcFile.exists()) { 
            throw new RuntimeException(srcFilePath + "不存在"); 
        } 
        if(!srcFile.isFile()){
           throw new RuntimeException(srcFilePath + "不是文件"); 
        }
        File zipFile = new File(srcFilePath+".zip"); 
        FileOutputStream fos = null;
        CheckedOutputStream cos = null;
        ZipOutputStream zos = null;
        try { 
            fos = new FileOutputStream(zipFile); 
            cos = new CheckedOutputStream(fos, new CRC32()); 
            zos = new ZipOutputStream(cos); 
//            zos.setEncoding("GBK");  //设置字符集

            zos.setMethod(ZipOutputStream.DEFLATED);  // 启用压缩  
            zos.setLevel(Deflater.BEST_COMPRESSION);   // 设置压缩级别为最强压缩  
            String baseDir = ""; 
            compressFile(srcFile, zos, baseDir); 
            zos.close(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally{
           IOUtils.closeQuietly(fos);
           IOUtils.closeQuietly(cos);
           IOUtils.closeQuietly(zos);
        }
    } 
   /** 
     * 压缩文件
     *  
     */ 
   /**
    * 压缩文件
    * @param file    待压缩文件
    * @param zos     压缩流
    * @param baseDir  文件标记
    */
    private static void compressFile(File file, ZipOutputStream zos, String baseDir) { 
        BufferedInputStream bis = null;
        FileInputStream fis = null;
        try { 
           fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis); 
            ZipEntry entry = new ZipEntry(baseDir + file.getName()); 
            zos.putNextEntry(entry); 
            int count; 
            byte[] buf = new byte[1024]; 
            while ((count = bis.read(buf)) != -1) { 
                zos.write(buf, 0, count); 
            } 
            zos.flush();   // 注,在使用缓冲流写压缩文件时,一个条件完后一定要刷新,不然可能有的内容就会存入到后面条目中去了  
            zos.closeEntry();  // 关闭当前ZIP条目并定位流以写入下一个条目  
        } catch (Exception e) { 
           e.printStackTrace();
        } finally{
           IOUtils.closeQuietly(fis);
           IOUtils.closeQuietly(bis);
        }
    } 

    /** 
      * @Description:  
      *     解压文件 
      * @param zipPath 被压缩文件,请使用绝对路径 
      * @param //targetPath 解压路径,解压后的文件将会放入此目录中,请使用绝对路径
      *         默认为压缩文件的路径的父目录为解压路径 
      * @param //encoding 解压编码
     */  
    public static void decompress(String zipPath) throws FileNotFoundException, ZipException, IOException {  
        // 获取解缩文件  
        File file = new File(zipPath);  
        if (!file.isFile()) {  
            throw new FileNotFoundException("要解压的文件不存在");  
        }  
        String targetPath = file.getParent();  
//        ZipFile zipFile = new ZipFile(file, "GBK");   // 实例化ZipFile对象  GBK
//        Enumeration<ZipEntry> files = zipFile.getEntries();  // 获取ZipFile中的条目

        ZipFile zipFile = new ZipFile(file, Charset.forName("GBK"));   // 实例化ZipFile对象  GBK
        Enumeration<? extends ZipEntry> files = zipFile.entries();  // 获取ZipFile中的条目

        ZipEntry entry = null;  // 迭代中的每一个条目  
        File outFile = null;  // 解压后的文件  
        BufferedInputStream bin = null;   // 读取压缩文件的输入流  
        BufferedOutputStream bout = null;  // 写入解压后文件的输出流  
        while (files.hasMoreElements()) {  
            entry = files.nextElement();  // 获取解压条目  
            // 实例化解压后文件对象  
            outFile = new File(targetPath + File.separator + entry.getName());  
            // 如果条目为目录,则跳向下一个  
            if (entry.getName().endsWith(File.separator)) {  
                outFile.mkdirs();  
                continue;  
            }  
            if (!outFile.getParentFile().exists()) { // 创建目录   
                outFile.getParentFile().mkdirs();  
            }  
            outFile.createNewFile();   // 创建新文件  
            if (!outFile.canWrite()) {   // 如果不可写,则跳向下一个条目  
                continue;  
            }  
            try {  
                // 获取读取条目的输入流  
                bin = new BufferedInputStream(zipFile.getInputStream(entry));  
                // 获取解压后文件的输出流  
                bout = new BufferedOutputStream(new FileOutputStream(outFile));  
                // 读取条目,并写入解压后文件  
                byte[] buffer = new byte[1024];  
                int readCount = -1;  
                while ((readCount = bin.read(buffer)) != -1) {  
                    bout.write(buffer, 0, readCount);  
                }  
            } finally {  
               IOUtils.closeQuietly(bin);
               IOUtils.closeQuietly(bout);
            }  
        }  
        zipFile.close();  //这个需要关闭不然删除不了
    }  
    
    /** 
     * @Description:  
     *     解压文件 
//     * @param zipPath 被压缩文件,请使用绝对路径
//     * @param targetPath 解压路径,解压后的文件将会放入此目录中,请使用绝对路径
     *         默认为压缩文件的路径的父目录为解压路径 
//     * @param encoding 解压编码
    */  
      
//    public static void main(String[] args) throws Exception{
//     String file = "C:\\FakePath\\412901197810083510_20180909_p2p_m.xml";
//     ZipUtil.compress(file,file+".zip");
//     ZipUtil.decompress(file+".zip");
//    }
    
}  

 

分享到:
评论

相关推荐

    S.E文件管理器 Solid Explorer File Manager 2.8.13 中文多语免费版.zip

    – 支持读取并解压ZIP,7ZIP,RAR和TAR文件,支持加密压缩文件 – 能够创建受密码保护的ZIP和7ZIP文件 – 云服务管理器,支持: Dropbox, Box, OneDrive, Google Drive, Sugarsync, Copy, Mediafire, Owncloud, ...

    Linux命令搜索工具linux-command.zip

    diff、diffstat、file、find、git、gitview、ln、locate、lsattr、mattrib、mc、mcopy、mdel、mdir、mktemp、mmove、mread、mren、mshowfat、mtools、mtoolstest、mv、od、paste、patch、rcp、rhmask、rm、slocate...

    网管教程 从入门到精通软件篇.txt

    Axx:ARJ压缩文件的分包序号文件,用于将一个大文件压至几个小的压缩包中(xx取01-99的数字) A3L:Authorware 3.x库文件 A4L:Authorware 4.x库文件 A5L:Authorware 5.x库文件 A3M,A4M:Authorware Macintosh...

    System Cleaner v7.6.23.680 官方正式版.zip

    值得一提的是如果你不想清理某文件也可以设定System Cleaner 2000把文件先放到一个目录暂存,或是执行ZIP把文件压缩起来。有定时的功能,可以让你订定大扫除的时间,或是定时清理你的硬盘。需要的朋友快来下载吧! ...

    JAVA_Thinking in Java(中文版 由yyc,spirit整理).chm

    10.8.2 用Zip进行多文件保存 10.8.3 Java归档(jar)实用程序 10.9 对象串联 10.9.1 寻找类 10.9.2 序列化的控制 10.9.3 利用“持久性” 10.10 总结 10.11 练习 第11章 运行期类型鉴定 11.1 对RTTI的需要 11.1.1 ...

    Ghost 8.3 系统备份软件

    首先选择打开一个备份文件(File/Open),这时备份中的文件就像资源管理器一样在程序界面窗口中列出,可以在其中非常方便地查看、打开文件,也可以查找文件,或者将某个文件删除(但不能删除目录)。 在 Ghost Explorer...

    Ghost 8.3 Enterprise

    首先选择打开一个备份文件(File/Open),这时备份中的文件就像资源管理器一样在程序界面窗口中列出,可以在其中非常方便地查看、打开文件,也可以查找文件,或者将某个文件删除(但不能删除目录)。  在 Ghost ...

    Thinking in Java(中文版 由yyc,spirit整理).chm

    10.8.2 用Zip进行多文件保存 10.8.3 Java归档(jar)实用程序 10.9 对象串联 10.9.1 寻找类 10.9.2 序列化的控制 10.9.3 利用“持久性” 10.10 总结 10.11 练习 第11章 运行期类型鉴定 11.1 对RTTI的需要 11.1.1 ...

    Getting-and-Cleaning-Data-Project:提交“获取和清洁数据”课程项目

    -“ ” download.file(url,destfile =“ ./Dataset.zip”) unzip(“ ./ Dataset.zip”,exdir =“ ./Dataset”) 将必要的文件读入R 以下代码读取R所需的zip文件中包含的文件 y_test &lt;-read.table(“ ./ ...

    datasciencemod3:数据科学模块 3 的课程项目

    数据科学模块 3 的课程项目 R 脚本 (run_analysis.R) 包含 run_analysis() 函数,该函数应用于执行...检查 zip 文件是否存在,将其解压缩到临时文件夹,并验证是否存在所需的数据文件 将所需文件读入 data.frames 使用

    Intel®Matrix Storage Manager v11.6.0.1030等7个版本合集、IDE切换为AHCI的方法

    4、(可选)安装Intel® Matrix Storage Manager(包含该程序的压缩包子目录名称包含&Manager;字样),安装后可通过该软件查看AHCI的详细工作状态。 本压缩包内容: 精简说明.txt Intel® Matrix Storage v11.2.0.1006 ...

    tidy_data_course_project

    -read.table(file_path,header = TRUE)” 要查看数据,请运行以下“查看(数据)”运行我的run_analysis.R代码的说明确保已下载此文件顶部的文件并将其解压缩到工作目录中。 您应该能够相应地导航到X_test文件:...

    Getting-and-Cleaning-Data:Coursera“获取和清理数据”课程的课程项目

    获取和清理数据:课程项目自述文件作者:克里斯·詹森##运行我的数据分析代码(假设和要求) 根据作业描述,我的代码假定数据文件已解压缩到 R 的工作目录中,并保持 zip 文件的目录结构。 源文件可从以下下载: : ...

    网站猎手2.0

    那么请您将System32.rar压缩包中文件解压缩并将缺少的文件复制到与webhunter.exe可执行文件的相同目录下即可。 2。查询 首先找出有漏洞系统的特征字串,比如DVBBS,“自由动力3”等等。这里,我以“自由动力3”为例...

Global site tag (gtag.js) - Google Analytics