当前位置:首页 > 开发 > 开源软件 > 正文

压缩文件夹

发表于: 2011-07-17   作者:cnjarchen   来源:转载   浏览:
摘要: //实现功能:将D:/upload文件夹的所有内容压缩到d:/test.zip import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStre
//实现功能:将D:/upload文件夹的所有内容压缩到d:/test.zip
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipTest {

    public static void makeZipfile(File file,String dir,ZipOutputStream zout) throws Exception{
         //定义文件位置
        if(dir.length()>0){
            dir = dir + "/" + file.getName();
        }else{
             dir = dir + file.getName();
        }

        if(file.isDirectory()){
           File[] files = file.listFiles();
           int i = 0;
           while(i<files.length){
               makeZipfile(files[i],dir,zout);
                i++;
            }
        }else{
            byte[] data = new byte[256];
            FileInputStream fin = new FileInputStream(file);
            BufferedInputStream bin = new BufferedInputStream(fin,256);
            ZipEntry entry = new ZipEntry(dir);
            zout.putNextEntry(entry);
            int b;
            while((b=bin.read(data,0,256))!=-1){
                zout.write(data,0,b);
            }
            fin.close();
            bin.close();  
       }
    }
    
    public static void main(String[] args){
        try {
                File file = new File("D:/upload");
                FileOutputStream fout = new FileOutputStream("d:/test.zip");
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                ZipOutputStream zout = new ZipOutputStream(bout);
                makeZipfile(file,"",zout);
                zout.close();
                bout.close();
                fout.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}

压缩文件夹

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号