`
yangmeng_3331
  • 浏览: 88057 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

使用apache的ant.jar进行压缩/解压缩文件

    博客分类:
  • Java
阅读更多
windows系统默认字符集为gbk,linux默认为utf-8,使用前视情况设定字符集。后来发现一个问题。当设定字符集为gbk后压缩一个文件在windows系统用winRAR打开只能显示非中文的文件或文件夹,但是手动解压后文件全部正常,用7zip打开全部正常。文章结尾有使用的ant.jar包。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

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

public class CompressFile {
	
	public final static String encoding = "gbk";  
	private static CompressFile instance = new CompressFile();
	private CompressFile() {
	}
	public static CompressFile getInstance() {
		return instance;
	}
	
	/**
	 * 压缩文件或者文件目录到指定的zip或者rar包
	 * @param inputFilename 要压缩的文件或者文件夹,如果是文件夹的话,会将文件夹下的所有文件包含子文件夹的内容进行压缩
	 * @param zipFilename 生成的zip或者rar文件的名称
	 * @throws IOException
	 */
	public synchronized void zip(String inputFilename, String zipFilename)
			throws Exception {
		zip(new File(inputFilename), zipFilename);
	}
	
	/**
	 * 压缩文件或者文件目录到指定的zip或者rar包,内部调用
	 * @param inputFile 参数为文件类型的要压缩的文件或者文件夹
	 * @param zipFilename 生成的zip或者rar文件的名称
	 * @throws IOException
	 */
	private synchronized void zip(File inputFile, String zipFilename) throws Exception {
		if (!inputFile.exists())
			return;
		//isNewFile用于判断是否是文件压缩,当时文件压缩时压缩完毕后删除创建的临时文件夹
		boolean isNewFile = false;
		if (!inputFile.isDirectory()) {
			//创建文件夹
			File file = new File(inputFile.getAbsolutePath().substring(0, inputFile.getAbsolutePath().lastIndexOf(".")));
			file.mkdirs();
			BufferedInputStream inBuff = null;
			BufferedOutputStream outBuff = null;
			//将文件信息拷贝到新建文件夹下
			try {
				File fileTmp = new File(file,inputFile.getName());
				inBuff = new BufferedInputStream(new FileInputStream(inputFile));
				outBuff = new BufferedOutputStream(new FileOutputStream(fileTmp));
				byte[] b = new byte[1024];
				int len;
				while ((len=inBuff.read(b))!=-1) {
					outBuff.write(b);
				}
				outBuff.flush();
			} finally{
				 if (inBuff != null)
	                inBuff.close();
	            if (outBuff != null)
	                outBuff.close();
			}
			inputFile = file;
			isNewFile = true;
		}
		//压缩文件
		Project project = new Project();
		Zip zip = new Zip();
		zip.setProject(project);
		zip.setDestFile(new File(zipFilename));
		//创建文件组
		FileSet fileSet = new FileSet();
		fileSet.setProject(project);
		fileSet.setDir(inputFile);
		zip.addFileset(fileSet);
		zip.setEncoding(CompressFile.encoding);
		zip.execute();
		if (isNewFile) {
			this.deleteDirectory(inputFile);
		}
	}
	
	/**
	 * 解压缩zip包
	 * @param zipFilePath zip文件路径
	 * @param targetPath 解压缩到的位置,如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下
	 * @throws IOException
	 */
	public synchronized void unzip(String zipFilePath, String targetPath) throws IOException {
		OutputStream os = null;
		InputStream is = null;
		ZipFile zipFile = null;
		try {
			//获取需要解压缩的文件
			zipFile = new ZipFile(zipFilePath,CompressFile.encoding);
			String directoryPath = "";
			if (null == targetPath || "".equals(targetPath)) {
				directoryPath = zipFilePath.substring(0, zipFilePath.lastIndexOf("."));
			} else {
				directoryPath = targetPath;
			}
			//获取压缩文件中的子目录
			Enumeration entryEnum = zipFile.getEntries();
			if (null != entryEnum) {
				ZipEntry zipEntry = null;
				while (entryEnum.hasMoreElements()) {
					zipEntry = (ZipEntry) entryEnum.nextElement();
					if (zipEntry.isDirectory()) {
						continue;
					}
					if (zipEntry.getSize() > 0) {
					// 文件
						File targetFile = this.buildFile(directoryPath + File.separator + zipEntry.getName(), false);
						os = new BufferedOutputStream(new FileOutputStream(targetFile));
						is = zipFile.getInputStream(zipEntry);
						byte[] buffer = new byte[4096];
						int readLen = 0;
						while ((readLen = is.read(buffer, 0, 4096)) >= 0) {
							os.write(buffer, 0, readLen);
						}
						os.flush();
						os.close();
					} else {
					// 空目录
					this.buildFile(directoryPath + File.separator+ zipEntry.getName(), true);
					}
				}
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			if(null != zipFile){
				zipFile = null;
			}
			if (null != is) {
				is.close();
			}
			if (null != os) {
				os.close();
			}
		}
	}
	
	/**
	 * 生产文件 如果文件所在路径不存在则生成路径
	 * @param fileName 文件名 带路径
	 * @param isDirectory 是否为路径
	 * @return
	 */
	private File buildFile(String fileName, boolean isDirectory) {
        File target = new File(fileName);
        if (isDirectory) {
            target.mkdirs();
        } else {
            if (!target.getParentFile().exists()) {
                target.getParentFile().mkdirs();
                target = new File(target.getAbsolutePath());
            }
        }
        return target;
    } 
	
	/**
	 * 删除文件 文件必须存在
	 * @param file
	 * @return
	 */
	private boolean deleteFile(File file) throws Exception {
		boolean flag = false;
		if (file.isFile() && file.exists()) {
			flag = file.delete();
		}
		return flag;
	}
	
	/**
	 * 删除文件夹 文件夹必须存在
	 * @param file
	 * @return
	 */
	private boolean deleteDirectory(File file) throws Exception { 
	    boolean flag = true;  
	    //删除文件夹下的所有文件(包括子目录)  
	    File[] files = file.listFiles();  
	    for (int i = 0; i < files.length; i++) {  
	        //删除子文件  
	        if (files[i].isFile()) {  
	            flag = deleteFile(files[i]); 
	            if (!flag) break;  
	        } //删除子目录  
	        else {  
	            flag = deleteDirectory(files[i]); 
	            if (!flag) break;  
	        }  
	    }
	    if (!flag)
	    	return false;
	    //删除当前目录  
	    if (file.delete())
	        return true;  
	    else
	        return false;
	}  
	
	public static void main(String[] args) {
		CompressFile bean = new CompressFile();
		try {
			//测试压缩文件 
			bean.zip("D:\\新建 文本文档.txt", "d:/测试.zip");
			bean.zip("D:\\新建文件夹", "d:/新建文件夹.zip");
			bean.zip("D:\\新建文件夹1", "d:/新建文件夹1.zip");
			//测试解压缩文件
			bean.unzip("d:\\测试.zip", "d:");
			bean.unzip("d:\\新建文件夹.zip", "d:");
			bean.unzip("d:/新建文件夹1.zip", "d:");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

分享到:
评论

相关推荐

    hadoop-lzo-master

    3.在本地测试 可以 执行 压缩及解压缩命令 下载 https://github.com/kevinweil/hadoop-lzo/zipball/master 解压包 export CFLAGS=-m64 export CXXFLAGS=-m64 //用于 hadoop0.20 ,所以1.0未必适用 进行build ant ...

    apache-ant-zip.jar

    Java自带的解压缩不支持中文路径,此开发包支持中文的解压缩

    java下的rar、zip等压缩、解缩工具

    java本身自带有zip格式的压缩解压api,但是对于含有中文的压缩文件无能为力,好在还有apache的ant可以解决zip文件的中文乱码问题。mucommander是一个可以支持zip、gzip、rar、tar、iso等格式的全能工具,这个包是...

    java压缩(zip)中文问题完美解决

    使用java压解有中文字符的文件乱码,apache项目中的ant.jar包可完美解决此问题,代码是用eclipse项目,项目下有ant.jar包,使用前请把ant.jar包导入.

    androi解压缩文件或文件夹

    1.Android 压缩文件,...完美支持文件名称和文件夹目录中存在中文的乱码问题 4.apache下的 ant.jar包 5.要点 mainifest中的权限 6. zipUtil在压缩和解压过程中的编码格式的指定"GBK" 7.项目可运行,希望大家给个好评

    axis1.4 部署解析webservie

    从它提示的地址下载软件包后,解压缩后在lib文件夹下,将xalan.jar和xmlsec-1.2.1.jar复制到TOMCAT_HOME\webapps\axis\WEB-INF\lib下。重新启动TOMCAT,再点击链接Validation进入页面后。将没有未找到包的提示了。 ...

    Java压缩及解压tar、tar.z格式文件

    Java压缩及解压tar、tar.z格式文件, 需要apache的包ant-1.7.1.jar 这个自己去搜索下下载

    fckedit编辑器

    将FCKeditor2.4解压缩,将整个目录FCKeditor复制到项目的根目录下,并将解压缩出来的文件夹fckeditor重命名为FCKeditor 目录结构为:tomcat/webapps/TestFCKeditor/FCKeditor 然后将FCKeditor-2.3.zip(java)...

    轻量级Java EE企业应用开发实战 源码 chapters 02

    (2) 安装Apache的Tomcat 6.0.16,不要使用安装文件安装,而是采用解压缩的安装方式。 安装Tomcat请参看第1章。安装完成后,将Tomcat安装路径的lib下的jsp-api.jar和servlet-api.jar两个JAR文件添加到CLASSPATH环境...

    轻量级Java EE企业应用开发实战 源码 chapters 01

    (2) 安装Apache的Tomcat 6.0.16,不要使用安装文件安装,而是采用解压缩的安装方式。 安装Tomcat请参看第1章。安装完成后,将Tomcat安装路径的lib下的jsp-api.jar和servlet-api.jar两个JAR文件添加到CLASSPATH环境...

    轻量级Java EE企业应用开发实战 源码 chapters 10

    (2) 安装Apache的Tomcat 6.0.16,不要使用安装文件安装,而是采用解压缩的安装方式。 安装Tomcat请参看第1章。安装完成后,将Tomcat安装路径的lib下的jsp-api.jar和servlet-api.jar两个JAR文件添加到CLASSPATH环境...

    struts2.0 第五章 第1,2节

    保证在d:盘根路径下安装Apache的Tomcat 5.5.20,不要使用安装文件安装,而是采用解压缩的安装方式。即:Tomcat的安装路径为d:\tomcat5520,文件夹的路径、名字都不要改变。 3.安装Ant1.7.0。将下载的Ant压缩文件解...

    struts 2.0 源码 第三章

    保证在d:盘根路径下安装Apache的Tomcat 5.5.20,不要使用安装文件安装,而是采用解压缩的安装方式。即:Tomcat的安装路径为d:\tomcat5520,文件夹的路径、名字都不要改变。 3.安装Ant1.7.0。将下载的Ant压缩文件解...

    LaToe:文本对象提取(LaToe)的布局注释

    拉托 ... 安装 Linux 克隆LaToe项目: ... cd latoe 用Ant构建LaToe: ... 解压缩C:\ ant \ 打开“ cmd”(搜索&gt; cmd) 更新路径: set PATH=%PATH% ; C: \a nt \b in ; 测试蚂蚁: ant -version Apache

    新版Android开发教程.rar

    o Apache Ant 1.6.5 or later for Linux and Mac, 1.7 or later for Windows o Not Not Not Not compatible with Gnu Compiler for Java (gcj) Note: Note: Note: Note: If JDK is already installed on your ...

    matlab集成c代码-GroovyLab:像MATLAB这样的用户友好型科学编程环境,使用Groovy作为脚本引擎以及Java9+的JShe

    步骤1下载并解压缩.zip下载文件。 步骤2为您的平台运行适当的脚本,例如,对于像Unix这样的系统的.sh脚本和对于Windows的.bat脚本。 使用Netbeans和ant构建 GroovyLab zip下载包含源代码和所有相关的库,以使用ant...

    cordova-plugin:Appodeal Cordova插件

    应该解压缩aar文件夹中的aar库并将其组合成ant库,您可以检查应如何在文件夹中的现有库上构建它。 打开plugin.xml文件,向下滚动到android平台标签的末尾,编辑source-file标签(应等于jar名称,已放入libs/...

Global site tag (gtag.js) - Google Analytics