码迷,mamicode.com
首页 > 编程语言 > 详细

Java Zip/Unzip Files 记录

时间:2015-03-15 23:00:22      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:zip   java   

最近项目中使用Java实现zip/unzip XML文件的功能,Java自带的API可以方便实现文件的压缩和解压缩,记录一下相关代码。

  1. 以源文件名zip压缩源文件到目标文件
public void zip(File src, File dest){
    InputStream in = null; 
    ZipOutputStream zos= null;
    try { 
        zos = new ZipOutputStream(new FileOutputStream(dest));
        ZipEntry ze= new ZipEntry(src.getName());
        zos.putNextEntry(ze);
        in = new FileInputStream(src);
        IOUtils.copy(in,zos); 
    } catch (IOException e) {
        LOG.error("fail to zip file: " + src.getName() + " to : " + dest.getName()); 
        throw e;
    } finally {
        if(null != zos){
            try {
                zos.closeEntry();
            } catch (IOException ex){
            }
        }
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(zos);
}
  1. 从源文件zip解压所有文件到目标文件夹
 public void unZip(File file, String outputFolder){ 
     File folder = new File(outputFolder);
     if(folder.exists() && folder.isFile()){ 
         throw IllegalArgumentException("Not an exists folder"); 
     }
     //create output directory is not exists
     if(!folder.exists() && !folder.mkdir()){
         throw IllegalStatusException("fail to create dest folder");
     }
     InputStream in = null; OutputStream out = null;
     ZipFile zipFile = new ZipFile(file); 
     Enumeration emu = zipFile.entries();
     while(emu.hasMoreElements()){
           ZipEntry entry = (ZipEntry)emu.nextElement();
           //建立目录
           if (entry.isDirectory()){
                new File(outputFolder + entry.getName()).mkdirs();
                    continue;
           }
           //文件拷贝
           InputStream is = zipFile.getInputStream(entry);
           File file = new File(outputFolder + entry.getName());
           //注意:zipfile读取文件是随机读取的,可能先读取一个文件,再读取文件夹,所以可能要先创建目录
           File parent = file.getParentFile();
           if(parent != null && (!parent.exists())){
               parent.mkdirs();
           }
           out = new FileOutputStream(file);
           IOUtils.closeQuietly(in);
           IOUtils.closeQuietly(out);
       } 
    }catch(IOException ex){
       LOG.error(ex.getMessage());
       throw ex;
    } finally {
       if(null != zipFile){
           try{
               zipFile.close();
           } catch (IOException e) {

           }
       }
       IOUtils.closeQuietly(in);
       IOUtils.closeQuietly(out);
    } 
}

这代码最主要就是文件太大的话,IOUtils的copy耗CPU比较高。

Java Zip/Unzip Files 记录

标签:zip   java   

原文地址:http://blog.csdn.net/cloud_ll/article/details/44282657

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!