java压缩文件,目录

package common;

import java.io.*;
import org.apache.tools.zip.*;


public class Zip
{    
    private static void zipDirectory(ZipOutputStream zos, String dirName,
            String basePath) throws Exception
    {
        File dir = new File(dirName);
        if (dir.exists())
        {
            File files[] = dir.listFiles();

            if (files.length > 0)
            {
                for (File file : files)
                {

                    if (file.isDirectory())
                    {
                        zipDirectory(zos, file.getPath(), basePath
                                + file.getName().substring(
                                        file.getName().lastIndexOf(
                                                File.separator) + 1)
                                + File.separator);
                    }
                    else
                        zipFile(zos, file.getPath(), basePath);
                }
            }
            else
            {
                ZipEntry ze = new ZipEntry(basePath);
                zos.putNextEntry(ze);
            }
        }
    }

    private static void  zipFile(ZipOutputStream zos, String filename,
            String basePath) throws Exception
    {
        File file = new File(filename);
    
        if (file.exists())
        {
            
            FileInputStream fis = new FileInputStream(filename);
            ZipEntry ze = new ZipEntry(basePath + file.getName());

            zos.putNextEntry(ze);
            byte[] buffer = new byte[8192];
            int count = 0;
            while ((count = fis.read(buffer)) > 0)
            {
                zos.write(buffer, 0, count);
            }
            fis.close();                    
        }
    }

    public static void compress(String zipFilename, String... paths)
            throws Exception
    {
        compress(new FileOutputStream(zipFilename), paths);

    }

    public static void  compress(OutputStream os, String... paths)
            throws Exception
    {
        ZipOutputStream zos = new ZipOutputStream(os);

        for (String path : paths)
        {
            if(path.equals("")) continue;
            java.io.File file = new java.io.File(path);
            if (file.exists())
            {

                if (file.isDirectory())
                {
                    zipDirectory(zos, file.getPath(), file.getName() + File.separator);
                }
                else
                {
                    zipFile(zos, file.getPath(), "");
                }
            }
        }
        zos.close();
    }
}


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
[本日志由 轻舞肥羊 于 2012-07-13 10:12 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: java zip
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.