Java实现文件压缩源码

package com.zyuc.zipfile;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

/**
 * 压缩文件到指定的目录
 * @title: FolderZip  
 * @description:
 * @author wangxw
 * @since  2012-4-11下午01:55:33   
 * @version 1.0
 */
public class FolderZip {

	public FolderZip() {}

	/**
	 * 
	 * 将指定目录的ZIP压缩文件解压到指定的目录
	 * @param folderZipPath ZIP压缩文件的路径
	 * @param zipFileName   ZIP压缩文件名字
	 * @param targetFileDir ZIP压缩文件要解压到的目录
	 * @return flag         布尔返回值
	 * 
	 */ 
	public static boolean zip(String folderZipPath, String targetFileDir, String zipFileName) {
		String targetFile = targetFileDir + "/" + zipFileName;
		File zipFile = null;
		File srcdir = new File(folderZipPath);
		//1.判断压缩文件是否存在
		if(!srcdir.exists()){
			 System.out.println(">>>>>>压缩文件【" + folderZipPath + "】不存在<<<<<<"); 
			 return false;
		}else{
			zipFile = new File(targetFile); // 压缩文件(带路径)
			System.out.println(">>>>>>压缩文件【" + folderZipPath + "】到【" + targetFile + " 】目录下<<<<<<");  
			//2.文件压缩开始
			Project p = new Project();
			Zip zip = new Zip();
			zip.setProject(p);
			zip.setDestFile(zipFile);
			FileSet fileSet = new FileSet();
			fileSet.setProject(p);
			fileSet.setDir(srcdir);
			zip.addFileset(fileSet);
			zip.execute();
		}
		return true;
	}

	/**
	 * 
	 * 测试用的Main方法
	 * 
	 */ 
	public static void main(String[] args) { 
		String folderZipPath = "D:\\test";    
        String targetFileDir = "D:\\test"; 
        String zipFileName = "test.zip"; 
        boolean flag = FolderZip.zip(folderZipPath,targetFileDir,zipFileName); 
        if(flag) {  
            System.out.println(">>>>>>压缩成功<<<<<<");  
        } else {  
            System.out.println(">>>>>>压缩失败<<<<<<");  
        }  
	}
}

你可能感兴趣的:(Java实现文件压缩源码)