JAVA实现把指定文件夹下的所有文件压缩成zip包

JAVA实现把指定文件夹下的所有文件压缩成zip包

    <div class="article_manage clearfix">
    <div class="article_r">
        <span class="link_postdate">2014-03-05 15:46</span>
        <span class="link_view" title="阅读次数">26657人阅读</span>
        <span class="link_comments" title="评论次数"> <a href="#comments" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_pinglun'])">评论</a>(13)</span>
        <span class="link_collect tracking-ad" data-mod="popu_171"> <a href="javascript:void(0);" onclick="javascript:collectArticle('JAVA%e5%ae%9e%e7%8e%b0%e6%8a%8a%e6%8c%87%e5%ae%9a%e6%96%87%e4%bb%b6%e5%a4%b9%e4%b8%8b%e7%9a%84%e6%89%80%e6%9c%89%e6%96%87%e4%bb%b6%e5%8e%8b%e7%bc%a9%e6%88%90zip%e5%8c%85','20550537');return false;" title="收藏" target="_blank">收藏</a></span>
         <span class="link_report"> <a href="#report" onclick="javascript:report(20550537,2);return false;" title="举报">举报</a></span>

    </div>
</div>
<div class="embody" style="display:none" id="embody">
    <span class="embody_t">本文章已收录于:</span>
    <div class="embody_c" id="lib" value="{&quot;err&quot;:0,&quot;msg&quot;:&quot;ok&quot;,&quot;data&quot;:[]}"></div>
</div>
<style type="text/css">        
        .embody{
            padding:10px 10px 10px;
            margin:0 -20px;
            border-bottom:solid 1px #ededed;                
        }
        .embody_b{
            margin:0 ;
            padding:10px 0;
        }
        .embody .embody_t,.embody .embody_c{
            display: inline-block;
            margin-right:10px;
        }
        .embody_t{
            font-size: 12px;
            color:#999;
        }
        .embody_c{
            font-size: 12px;
        }
        .embody_c img,.embody_c em{
            display: inline-block;
            vertical-align: middle;               
        }
         .embody_c img{               
            width:30px;
            height:30px;
        }
        .embody_c em{
            margin: 0 20px 0 10px;
            color:#333;
            font-style: normal;
        }
</style>
<script type="text/javascript">
    $(function () {
        try
        {
            var lib = eval("("+$("#lib").attr("value")+")");
            var html = "";
            if (lib.err == 0) {
                $.each(lib.data, function (i) {
                    var obj = lib.data[i];
                    //html += '<img src="' + obj.logo + '"/>' + obj.name + "&nbsp;&nbsp;";
                    html += ' <a href="' + obj.url + '" target="_blank">';
                    html += ' <img src="' + obj.logo + '">';
                    html += ' <em><b>' + obj.name + '</b></em>';
                    html += ' </a>';
                });
                if (html != "") {
                    setTimeout(function () {
                        $("#lib").html(html);                      
                        $("#embody").show();
                    }, 100);
                }
            }      
        } catch (err)
        { }

    });
</script>
  <div class="category clearfix">
    <div class="category_l">
       <img src="http://static.blog.csdn.net/images/category_icon.jpg">
        <span>分类:</span>
    </div>
    <div class="category_r">
                <label onclick="GetCategoryArticles('1478041','sxdtzhaoxinguo','top','20550537');">
                    <span onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_fenlei']);">Java后端技术<em>(80)</em></span>
                  <img class="arrow-down" src="http://static.blog.csdn.net/images/arrow_triangle _down.jpg" style="display:inline;">
                  <img class="arrow-up" src="http://static.blog.csdn.net/images/arrow_triangle_up.jpg" style="display:none;">
                    <div class="subItem">
                        <div class="subItem_t"><a href="http://blog.csdn.net/sxdtzhaoxinguo/article/category/1478041" target="_blank">作者同类文章</a><i class="J_close">X</i></div>
                        <ul class="subItem_l" id="top_1478041">                            
                        </ul>
                    </div>
                </label>                    
    </div>
</div>
<script type="text/javascript" src="http://static.blog.csdn.net/scripts/category.js"></script>  
    <div class="bog_copyright">         
        <p class="copyright_p">版权声明:本文为博主原创文章,未经博主允许不得转载。</p>
    </div>

1.代码如下:

  1. <span style=“font-size:18px;background-color: rgb(204, 204, 204);”>package cn.gov.csrc.base.util;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import java.util.zip.ZipEntry;  
  11. import java.util.zip.ZipOutputStream;  
  12. /** 
  13.  * 将文件夹下面的文件 
  14.  * 打包成zip压缩文件 
  15.  *  
  16.  * @author admin 
  17.  * 
  18.  */  
  19. public final class FileToZip {  
  20.   
  21.     private FileToZip(){}  
  22.       
  23.     /** 
  24.      * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下 
  25.      * @param sourceFilePath :待压缩的文件路径 
  26.      * @param zipFilePath :压缩后存放路径 
  27.      * @param fileName :压缩后文件的名称 
  28.      * @return 
  29.      */  
  30.     public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){  
  31.         boolean flag = false;  
  32.         File sourceFile = new File(sourceFilePath);  
  33.         FileInputStream fis = null;  
  34.         BufferedInputStream bis = null;  
  35.         FileOutputStream fos = null;  
  36.         ZipOutputStream zos = null;  
  37.           
  38.         if(sourceFile.exists() == false){  
  39.             System.out.println(”待压缩的文件目录:”+sourceFilePath+“不存在.”);  
  40.         }else{  
  41.             try {  
  42.                 File zipFile = new File(zipFilePath + “/” + fileName +“.zip”);  
  43.                 if(zipFile.exists()){  
  44.                     System.out.println(zipFilePath + ”目录下存在名字为:” + fileName +“.zip” +“打包文件.”);  
  45.                 }else{  
  46.                     File[] sourceFiles = sourceFile.listFiles();  
  47.                     if(null == sourceFiles || sourceFiles.length<1){  
  48.                         System.out.println(”待压缩的文件目录:” + sourceFilePath + “里面不存在文件,无需压缩.”);  
  49.                     }else{  
  50.                         fos = new FileOutputStream(zipFile);  
  51.                         zos = new ZipOutputStream(new BufferedOutputStream(fos));  
  52.                         byte[] bufs = new byte[1024*10];  
  53.                         for(int i=0;i<sourceFiles.length;i++){  
  54.                             //创建ZIP实体,并添加进压缩包  
  55.                             ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());  
  56.                             zos.putNextEntry(zipEntry);  
  57.                             //读取待压缩的文件并写进压缩包里  
  58.                             fis = new FileInputStream(sourceFiles[i]);  
  59.                             bis = new BufferedInputStream(fis, 1024*10);  
  60.                             int read = 0;  
  61.                             while((read=bis.read(bufs, 01024*10)) != -1){  
  62.                                 zos.write(bufs,0,read);  
  63.                             }  
  64.                         }  
  65.                         flag = true;  
  66.                     }  
  67.                 }  
  68.             } catch (FileNotFoundException e) {  
  69.                 e.printStackTrace();  
  70.                 throw new RuntimeException(e);  
  71.             } catch (IOException e) {  
  72.                 e.printStackTrace();  
  73.                 throw new RuntimeException(e);  
  74.             } finally{  
  75.                 //关闭流  
  76.                 try {  
  77.                     if(null != bis) bis.close();  
  78.                     if(null != zos) zos.close();  
  79.                 } catch (IOException e) {  
  80.                     e.printStackTrace();  
  81.                     throw new RuntimeException(e);  
  82.                 }  
  83.             }  
  84.         }  
  85.         return flag;  
  86.     }  
  87.       
  88.     public static void main(String[] args){  
  89.         String sourceFilePath = ”D:\\TestFile”;  
  90.         String zipFilePath = ”D:\\tmp”;  
  91.         String fileName = ”12700153file”;  
  92.         boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);  
  93.         if(flag){  
  94.             System.out.println(”文件打包成功!”);  
  95.         }else{  
  96.             System.out.println(”文件打包失败!”);  
  97.         }  
  98.     }  
  99.       
  100. }  
  101. </span>  
package cn.gov.csrc.base.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * 将文件夹下面的文件
 * 打包成zip压缩文件
 * 
 * @author admin
 *
 */
public final class FileToZip {

    private FileToZip(){}

    /**
     * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
     * @param sourceFilePath :待压缩的文件路径
     * @param zipFilePath :压缩后存放路径
     * @param fileName :压缩后文件的名称
     * @return
     */
    public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){
        boolean flag = false;
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;

        if(sourceFile.exists() == false){
            System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");
        }else{
            try {
                File zipFile = new File(zipFilePath + "/" + fileName +".zip");
                if(zipFile.exists()){
                    System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");
                }else{
                    File[] sourceFiles = sourceFile.listFiles();
                    if(null == sourceFiles || sourceFiles.length<1){
                        System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
                    }else{
                        fos = new FileOutputStream(zipFile);
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
                        byte[] bufs = new byte[1024*10];
                        for(int i=0;i<sourceFiles.length;i++){
                            //创建ZIP实体,并添加进压缩包
                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                            zos.putNextEntry(zipEntry);
                            //读取待压缩的文件并写进压缩包里
                            fis = new FileInputStream(sourceFiles[i]);
                            bis = new BufferedInputStream(fis, 1024*10);
                            int read = 0;
                            while((read=bis.read(bufs, 0, 1024*10)) != -1){
                                zos.write(bufs,0,read);
                            }
                        }
                        flag = true;
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally{
                //关闭流
                try {
                    if(null != bis) bis.close();
                    if(null != zos) zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return flag;
    }

    public static void main(String[] args){
        String sourceFilePath = "D:\\TestFile";
        String zipFilePath = "D:\\tmp";
        String fileName = "12700153file";
        boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);
        if(flag){
            System.out.println("文件打包成功!");
        }else{
            System.out.println("文件打包失败!");
        }
    }

}


2.结果如下:

文件打包成功!


3.到D:/tmp下查看,你会发现生成了一个zip压缩包.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值