java 实现对文件文件夹压缩、解压

View Code
public class CompressUtil
{

    /**
     * <一句话功能简述> <功能详细描述>
     * 
     * @param args
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    public static void main(String[] args) throws Exception
    {
        // TODO Auto-generated method stub
        compress("e:\\app", "e:");
    }

    public static void compress(String srcPath, String destDir) throws Exception
    {
        File file = new File(srcPath);
        
        if (!file.exists())
        {
            throw new Exception(srcPath + "文件不存在");
        }
        else
        {
            String fileName = file.getName();
            File zipFile = file;
            ZipOutputStream out = null;
            if (file.isFile())
            {
                String zipFilePath  = destDir + fileName.substring(0, fileName.lastIndexOf(".")) + ".zip";
                zipFile = new File(zipFilePath);
                // 压缩文件的名字
                FileOutputStream fos = new FileOutputStream(zipFile); 
                out = new ZipOutputStream(fos);
                
                compressFile(file, out, destDir);
            }
            else
            {
                String zipFilePath = fileName + ".zip";
                zipFile = new File(zipFilePath);
                // 压缩文件的名字
                out = new ZipOutputStream(new FileOutputStream(zipFile));
                
                compressDir(file, out, destDir);
            }
            out.flush();
            out.close();
            
        }

    }

    public static void compressFile(File file, ZipOutputStream out, String destDir) throws Exception
    {
        int bufferSize = 1024;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file), bufferSize);

        // 被压缩文件的名字
        ZipEntry entry = new ZipEntry(file.getName());
        out.putNextEntry(entry);

        int cunt = 0;
        byte[] bytes = new byte[1024];
        while ((cunt = in.read(bytes)) != -1)
        {
            out.write(bytes, 0, cunt);
        }
        in.close();
    }

    public static void compressDir(File file, ZipOutputStream out, String destDir) throws Exception
    {
        File[] files = file.listFiles();

        for (File tmp : files)
        {
            if (tmp.isDirectory())
            {
                compressDir(tmp, out, destDir + File.separator + tmp.getName());
            }
            else
            {
                compressFile(tmp, out, destDir);
            }
        }
    }
}

 这个类压缩目录还有点小问题,有待修改……

View Code
posted @ 2012-11-21 21:52  刺客XIII  阅读(293)  评论(0编辑  收藏  举报