利用apache ant 包进行压缩、解压缩zip,归档tar,解档tar,压缩tar.gz解压tar.gz

 最近用到了利用java进行一序列压缩解压缩,jdk也自带了,这里我就不用它了。本例用到的开源包是apahce ant.jar。我上传了。希望对大家有帮组。
引用
Java压缩zip,解压缩zip
Java代码
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.util.Enumeration;  
  8. import java.util.zip.CRC32;  
  9. import java.util.zip.CheckedOutputStream;  
  10.   
  11. import org.apache.tools.zip.ZipEntry;  
  12. import org.apache.tools.zip.ZipFile;  
  13. import org.apache.tools.zip.ZipOutputStream;  
  14.   
  15.   
  16. /** 
  17.  * 利用Apache ant.jar中的zip包进行Zip压缩和解压 
  18.  */  
  19. public class XZouZip {  
  20.     /** 
  21.      * 测试压缩 
  22.      */  
  23.     public void testZip(){  
  24.           
  25.         File srcFile = new File("c:/upload");//要压缩的文件对象   
  26.           
  27.         File targetZipFile = new File("c:/upload.zip");//压缩后的文件名   
  28.           
  29.         ZipOutputStream out = null;  
  30.           
  31.         boolean boo = false;//是否压缩成功   
  32.           
  33.         try{  
  34.               
  35.             CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(  
  36.                     targetZipFile), new CRC32());  
  37.              out = new ZipOutputStream(cos);  
  38.               
  39.             //out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("c:/uploadd.zip")));   
  40.               
  41.             zip(srcFile, out, ""true);  
  42.               
  43.             boo = true;  
  44.               
  45.         }catch(IOException ex){  
  46.             throw new RuntimeException(ex);  
  47.         }finally{  
  48.               
  49.             try{  
  50.                 if(out!=null)  
  51.                     out.close();  
  52.             }catch(IOException ex){  
  53.                 throw new RuntimeException("关闭Zip输出流出现异常",ex);  
  54.             }finally{  
  55.                 //清理操作   
  56.                 if(!boo && targetZipFile.exists())//压缩不成功,   
  57.                     targetZipFile.delete();  
  58.             }  
  59.               
  60.         }  
  61.   
  62.     }  
  63.       
  64.     /** 
  65.      * 测试解压缩 
  66.      */  
  67.     public void testUnZip(){  
  68.           
  69.         File srcZipFile = new File("c:/upload.zip");//要解压缩的zip文件对象   
  70.           
  71.         String destDir = "c:/a";//将解压文件对象放置a目录中   
  72.           
  73.         boolean boo = false;//是否压缩成功   
  74.           
  75.         try {  
  76.             unZip(srcZipFile,destDir);  
  77.             boo = true;  
  78.         } catch (IOException e) {  
  79.             throw new RuntimeException(e);  
  80.         }finally{  
  81.             //清理操作   
  82.             if(!boo)  
  83.                 deleteDirectory(new File(destDir));//目标文件夹 。清理   
  84.               
  85.         }  
  86.           
  87.     }  
  88.     public static void main(String[] args) throws IOException {  
  89.           
  90.         XZouZip tool = new XZouZip();  
  91.           
  92.         tool.testZip();  
  93.           
  94.         //tool.testUnZip();   
  95.           
  96.           
  97.     }  
  98.       
  99.       
  100.       
  101.     /** 
  102.      * 压缩zip文件 
  103.      * @param file 压缩的文件对象 
  104.      * @param out 输出ZIP流 
  105.      * @param dir 相对父目录名称 
  106.      * @param boo 是否把空目录压缩进去 
  107.      */  
  108.     public void zip(File file,ZipOutputStream out,String dir,boolean boo) throws IOException{  
  109.           
  110.         if(file.isDirectory()){//是目录   
  111.               
  112.             File []listFile = file.listFiles();//得出目录下所有的文件对象   
  113.               
  114.             if(listFile.length == 0 && boo){//空目录压缩   
  115.                   
  116.                 out.putNextEntry(new ZipEntry(dir + file.getName() + "/"));//将实体放入输出ZIP流中   
  117.                 System.out.println("压缩." + dir + file.getName() + "/");  
  118.                 return;  
  119.             }else{  
  120.                   
  121.                 for(File cfile: listFile){  
  122.                       
  123.                     zip(cfile,out,dir + file.getName() + "/",boo);//递归压缩   
  124.                 }  
  125.             }  
  126.               
  127.         }else if(file.isFile()){//是文件   
  128.               
  129.             System.out.println("压缩." + dir + file.getName() + "/");  
  130.               
  131.             byte[] bt = new byte[2048*2];  
  132.               
  133.             ZipEntry ze = new ZipEntry(dir+file.getName());//构建压缩实体   
  134.             //设置压缩前的文件大小   
  135.             ze.setSize(file.length());  
  136.               
  137.             out.putNextEntry(ze);将实体放入输出ZIP流中   
  138.               
  139.             FileInputStream fis = null;  
  140.               
  141.             try{  
  142.                   
  143.                 fis = new FileInputStream(file);  
  144.                   
  145.                 int i=0;  
  146.                   
  147.                 while((i = fis.read(bt)) != -1) {//循环读出并写入输出Zip流中   
  148.     
  149.                     out.write(bt, 0, i);  
  150.                 }  
  151.                   
  152.             }catch(IOException ex){  
  153.                 throw new IOException("写入压缩文件出现异常",ex);  
  154.             }finally{  
  155.                   
  156.                 try{  
  157.                     if (fis != null)  
  158.                         fis.close();//关闭输入流   
  159.                       
  160.                 }catch(IOException ex){  
  161.                       
  162.                     throw new IOException("关闭输入流出现异常");  
  163.                 }  
  164.   
  165.             }             
  166.         }  
  167.           
  168.     }  
  169.       
  170.     /** 
  171.      * 解压缩zipFile 
  172.      * @param file 要解压的zip文件对象 
  173.      * @param outputDir 要解压到某个指定的目录下 
  174.      * @throws IOException 
  175.      */  
  176.     public void unZip(File file,String outputDir) throws IOException {  
  177.           
  178.           
  179.         ZipFile zipFile = null;  
  180.           
  181.         try {  
  182.               
  183.             zipFile =  new ZipFile(file);     
  184.               
  185.             createDirectory(outputDir,null);//创建输出目录   
  186.   
  187.             Enumeration<?> enums = zipFile.getEntries();  
  188.               
  189.             while(enums.hasMoreElements()){  
  190.                   
  191.                 ZipEntry entry = (ZipEntry) enums.nextElement();  
  192.                   
  193.                 System.out.println("解压." +  entry.getName());  
  194.                   
  195.                 if(entry.isDirectory()){//是目录   
  196.                       
  197.                     createDirectory(outputDir,entry.getName());//创建空目录   
  198.                       
  199.                 }else{//是文件   
  200.                       
  201.                     File tmpFile = new File(outputDir + "/" + entry.getName());  
  202.                       
  203.                     createDirectory(tmpFile.getParent() + "/",null);//创建输出目录   
  204.                       
  205.                     InputStream in = null;  
  206.                       
  207.                     OutputStream out = null;  
  208.                       
  209.                     try{  
  210.                         in = zipFile.getInputStream(entry);;  
  211.                           
  212.                         out = new FileOutputStream(tmpFile);  
  213.                           
  214.                         int length = 0;  
  215.                           
  216.                         byte[] b = new byte[2048];  
  217.                           
  218.                         while((length = in.read(b)) != -1){  
  219.                             out.write(b, 0, length);  
  220.                         }  
  221.                       
  222.                     }catch(IOException ex){  
  223.                         throw ex;  
  224.                     }finally{  
  225.                         if(in!=null)  
  226.                             in.close();  
  227.                         if(out!=null)  
  228.                             out.close();  
  229.                     }  
  230.                       
  231.                 }  
  232.                   
  233.             }  
  234.               
  235.         } catch (IOException e) {  
  236.             throw new IOException("解压缩文件出现异常",e);  
  237.         } finally{  
  238.             try{  
  239.                 if(zipFile != null){  
  240.                     zipFile.close();  
  241.                 }  
  242.             }catch(IOException ex){  
  243.                 throw new IOException("关闭zipFile出现异常",ex);  
  244.             }  
  245.         }  
  246.           
  247.           
  248.     }  
  249.       
  250.     /** 
  251.      * 构建目录 
  252.      * @param outputDir 
  253.      * @param subDir 
  254.      */  
  255.     public void createDirectory(String outputDir,String subDir){  
  256.           
  257.         File file = new File(outputDir);  
  258.           
  259.         if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空   
  260.               
  261.             file = new File(outputDir + "/" + subDir);  
  262.         }  
  263.           
  264.         if(!file.exists()){  
  265.               
  266.             file.mkdirs();  
  267.         }  
  268.           
  269.     }  
  270.       
  271.     /** 
  272.      * 清理文件(目录或文件) 
  273.      * @param file 
  274.      */  
  275.     public void deleteDirectory(File file){  
  276.           
  277.         if(file.isFile()){  
  278.               
  279.             file.delete();//清理文件   
  280.         }else{  
  281.               
  282.             File list[] = file.listFiles();  
  283.               
  284.             if(list!=null){  
  285.               
  286.                 for(File f: list){  
  287.                     deleteDirectory(f);  
  288.                 }  
  289.                 file.delete();//清理目录   
  290.             }  
  291.               
  292.         }  
  293.           
  294.     }  
  295. }  
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 java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

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


/**
 * 利用Apache ant.jar中的zip包进行Zip压缩和解压
 */
public class XZouZip {
	/**
	 * 测试压缩
	 */
	public void testZip(){
		
		File srcFile = new File("c:/upload");//要压缩的文件对象
		
		File targetZipFile = new File("c:/upload.zip");//压缩后的文件名
		
		ZipOutputStream out = null;
		
		boolean boo = false;//是否压缩成功
		
		try{
			
			CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(
					targetZipFile), new CRC32());
			 out = new ZipOutputStream(cos);
			
			//out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("c:/uploadd.zip")));
			
			zip(srcFile, out, "", true);
			
			boo = true;
			
		}catch(IOException ex){
			throw new RuntimeException(ex);
		}finally{
			
			try{
				if(out!=null)
					out.close();
			}catch(IOException ex){
				throw new RuntimeException("关闭Zip输出流出现异常",ex);
			}finally{
				//清理操作
				if(!boo && targetZipFile.exists())//压缩不成功,
					targetZipFile.delete();
			}
			
		}

	}
	
	/**
	 * 测试解压缩
	 */
	public void testUnZip(){
		
		File srcZipFile = new File("c:/upload.zip");//要解压缩的zip文件对象
		
		String destDir = "c:/a";//将解压文件对象放置a目录中
		
		boolean boo = false;//是否压缩成功
		
		try {
			unZip(srcZipFile,destDir);
			boo = true;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally{
			//清理操作
			if(!boo)
				deleteDirectory(new File(destDir));//目标文件夹 。清理
			
		}
		
	}
	public static void main(String[] args) throws IOException {
		
		XZouZip tool = new XZouZip();
		
		tool.testZip();
		
		//tool.testUnZip();
		
		
	}
	
	
	
	/**
	 * 压缩zip文件
	 * @param file 压缩的文件对象
	 * @param out 输出ZIP流
	 * @param dir 相对父目录名称
	 * @param boo 是否把空目录压缩进去
	 */
	public void zip(File file,ZipOutputStream out,String dir,boolean boo) throws IOException{
		
		if(file.isDirectory()){//是目录
			
			File []listFile = file.listFiles();//得出目录下所有的文件对象
			
			if(listFile.length == 0 && boo){//空目录压缩
				
				out.putNextEntry(new ZipEntry(dir + file.getName() + "/"));//将实体放入输出ZIP流中
				System.out.println("压缩." + dir + file.getName() + "/");
				return;
			}else{
				
				for(File cfile: listFile){
					
					zip(cfile,out,dir + file.getName() + "/",boo);//递归压缩
				}
			}
			
		}else if(file.isFile()){//是文件
			
			System.out.println("压缩." + dir + file.getName() + "/");
			
			byte[] bt = new byte[2048*2];
			
            ZipEntry ze = new ZipEntry(dir+file.getName());//构建压缩实体
            //设置压缩前的文件大小
            ze.setSize(file.length());
            
            out.putNextEntry(ze);将实体放入输出ZIP流中
            
            FileInputStream fis = null;
            
            try{
            	
            	fis = new FileInputStream(file);
            	
            	int i=0;
                
                while((i = fis.read(bt)) != -1) {//循环读出并写入输出Zip流中
  
                    out.write(bt, 0, i);
                }
            	
            }catch(IOException ex){
            	throw new IOException("写入压缩文件出现异常",ex);
            }finally{
            	
            	try{
            		if (fis != null)
            			fis.close();//关闭输入流
            		
            	}catch(IOException ex){
            		
            		throw new IOException("关闭输入流出现异常");
            	}

            }           
		}
		
	}
	
	/**
	 * 解压缩zipFile
	 * @param file 要解压的zip文件对象
	 * @param outputDir 要解压到某个指定的目录下
	 * @throws IOException
	 */
	public void unZip(File file,String outputDir) throws IOException {
		
		
		ZipFile zipFile = null;
		
		try {
			
			zipFile =  new ZipFile(file);	
			
			createDirectory(outputDir,null);//创建输出目录

			Enumeration<?> enums = zipFile.getEntries();
			
			while(enums.hasMoreElements()){
				
				ZipEntry entry = (ZipEntry) enums.nextElement();
				
				System.out.println("解压." +  entry.getName());
				
				if(entry.isDirectory()){//是目录
					
					createDirectory(outputDir,entry.getName());//创建空目录
					
				}else{//是文件
					
					File tmpFile = new File(outputDir + "/" + entry.getName());
					
					createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
					
					InputStream in = null;
					
					OutputStream out = null;
					
					try{
						in = zipFile.getInputStream(entry);;
						
						out = new FileOutputStream(tmpFile);
						
						int length = 0;
						
						byte[] b = new byte[2048];
						
						while((length = in.read(b)) != -1){
							out.write(b, 0, length);
						}
					
					}catch(IOException ex){
						throw ex;
					}finally{
						if(in!=null)
							in.close();
						if(out!=null)
							out.close();
					}
					
				}
				
			}
			
		} catch (IOException e) {
			throw new IOException("解压缩文件出现异常",e);
		} finally{
			try{
				if(zipFile != null){
					zipFile.close();
				}
			}catch(IOException ex){
				throw new IOException("关闭zipFile出现异常",ex);
			}
		}
		
		
	}
	
	/**
	 * 构建目录
	 * @param outputDir
	 * @param subDir
	 */
	public void createDirectory(String outputDir,String subDir){
		
		File file = new File(outputDir);
		
		if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空
			
			file = new File(outputDir + "/" + subDir);
		}
		
		if(!file.exists()){
			
			file.mkdirs();
		}
		
	}
	
	/**
	 * 清理文件(目录或文件)
	 * @param file
	 */
	public void deleteDirectory(File file){
		
		if(file.isFile()){
			
			file.delete();//清理文件
		}else{
			
			File list[] = file.listFiles();
			
			if(list!=null){
			
				for(File f: list){
					deleteDirectory(f);
				}
				file.delete();//清理目录
			}
			
		}
		
	}
}


引用
Java压缩解压缩zip利用ant.更简单
Java代码
  1. import java.io.File;  
  2.   
  3. import org.apache.tools.ant.Project;  
  4. import org.apache.tools.ant.taskdefs.Expand;  
  5. import org.apache.tools.ant.taskdefs.Zip;  
  6. import org.apache.tools.ant.types.FileSet;  
  7.   
  8.   
  9. /** 
  10.  * 利用Apache ant.jar中的ant包进行Zip压缩和解压 
  11.  * 这个更为简单 
  12.  */  
  13. public class XZouZipByAnt {  
  14.   
  15.     public static void main(String[] args) {  
  16.           
  17.         XZouZipByAnt jzb = new XZouZipByAnt();  
  18.           
  19.         jzb.zip("c:/upload""c:/upload.zip");  
  20.           
  21.         //jzb.unZip("c:/a", "c:/upload.zip");   
  22.     }  
  23.       
  24.     /** 
  25.      * 解压缩 
  26.      * @param destDir 生成的目标目录下   c:/a 
  27.      * @param sourceZip 源zip文件      c:/upload.zip 
  28.      * 结果则是 将upload.zip文件解压缩到c:/a目录下 
  29.      */  
  30.     public void unZip(String destDir,String sourceZip){  
  31.           
  32.          try {  
  33.             Project prj1 = new Project();  
  34.               
  35.             Expand expand = new Expand();  
  36.               
  37.             expand.setProject(prj1);  
  38.               
  39.             expand.setSrc(new File(sourceZip));  
  40.               
  41.             expand.setOverwrite(false);//是否覆盖   
  42.   
  43.             File f = new File(destDir);  
  44.               
  45.             expand.setDest(f);  
  46.               
  47.             expand.execute();  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         }  
  51.     }  
  52.   
  53.   
  54.     /** 
  55.      * 压缩 
  56.      *  
  57.      * @param sourceFile 
  58.      *            压缩的源文件 如: c:/upload 
  59.      * @param targetZip 
  60.      *            生成的目标文件 如:c:/upload.zip 
  61.      */  
  62.     public void zip(String sourceFile,String targetZip){  
  63.           
  64.           Project prj = new Project();  
  65.             
  66.           Zip zip = new Zip();  
  67.             
  68.           zip.setProject(prj);  
  69.             
  70.           zip.setDestFile(new File(targetZip));//设置生成的目标zip文件File对象   
  71.             
  72.           FileSet fileSet = new FileSet();  
  73.             
  74.           fileSet.setProject(prj);  
  75.             
  76.           fileSet.setDir(new File(sourceFile));//设置将要进行压缩的源文件File对象   
  77.             
  78.           //fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹,只压缩目录中的所有java文件   
  79.             
  80.           //fileSet.setExcludes("**/*.java"); //排除哪些文件或文件夹,压缩所有的文件,排除java文件   
  81.             
  82.             
  83.           zip.addFileset(fileSet);  
  84.   
  85.           zip.execute();  
  86.   
  87.     }  
  88. }  
import java.io.File;

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


/**
 * 利用Apache ant.jar中的ant包进行Zip压缩和解压
 * 这个更为简单
 */
public class XZouZipByAnt {

	public static void main(String[] args) {
		
		XZouZipByAnt jzb = new XZouZipByAnt();
		
		jzb.zip("c:/upload", "c:/upload.zip");
		
		//jzb.unZip("c:/a", "c:/upload.zip");
	}
	
	/**
	 * 解压缩
	 * @param destDir 生成的目标目录下   c:/a
	 * @param sourceZip 源zip文件      c:/upload.zip
	 * 结果则是 将upload.zip文件解压缩到c:/a目录下
	 */
	public void unZip(String destDir,String sourceZip){
		
		 try {
			Project prj1 = new Project();
			
			Expand expand = new Expand();
			
			expand.setProject(prj1);
			
			expand.setSrc(new File(sourceZip));
			
			expand.setOverwrite(false);//是否覆盖

			File f = new File(destDir);
			
			expand.setDest(f);
			
			expand.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 压缩
	 * 
	 * @param sourceFile
	 *            压缩的源文件 如: c:/upload
	 * @param targetZip
	 *            生成的目标文件 如:c:/upload.zip
	 */
	public void zip(String sourceFile,String targetZip){
		
		  Project prj = new Project();
		  
		  Zip zip = new Zip();
		  
		  zip.setProject(prj);
		  
		  zip.setDestFile(new File(targetZip));//设置生成的目标zip文件File对象
		  
		  FileSet fileSet = new FileSet();
		  
		  fileSet.setProject(prj);
		  
		  fileSet.setDir(new File(sourceFile));//设置将要进行压缩的源文件File对象
		  
		  //fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹,只压缩目录中的所有java文件
		  
		  //fileSet.setExcludes("**/*.java"); //排除哪些文件或文件夹,压缩所有的文件,排除java文件
		  
		  
		  zip.addFileset(fileSet);

		  zip.execute();

	}
}


引用
通过 Apache Tool 进行JAVA tar || tar.gz
Java代码 
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.util.zip.GZIPInputStream;  
  10. import java.util.zip.GZIPOutputStream;  
  11.   
  12. import org.apache.tools.tar.TarEntry;  
  13. import org.apache.tools.tar.TarInputStream;  
  14. import org.apache.tools.tar.TarOutputStream;  
  15.   
  16.   
  17. /** 
  18.  * 通过 Apache Tool 进行JAVA tar || tar.gz 
  19.  */  
  20. public class XZouTarAndGz {  
  21.   
  22.   
  23.     /** 
  24.      * 测试归档tar文件 
  25.      */  
  26.     public File testTar(){  
  27.           
  28.         File srcFile = new File("c:/upload");//要归档的文件对象   
  29.           
  30.         File targetTarFile = new File("c:/upload.tar");//归档后的文件名   
  31.           
  32.         TarOutputStream out = null;  
  33.           
  34.         boolean boo = false;//是否压缩成功   
  35.           
  36.         try{  
  37.             out = new TarOutputStream(new BufferedOutputStream(new FileOutputStream(targetTarFile)));  
  38.               
  39.             tar(srcFile, out, ""true);  
  40.               
  41.             boo = true;  
  42.               
  43.             //归档成功   
  44.               
  45.             return targetTarFile;  
  46.               
  47.         }catch(IOException ex){  
  48.             throw new RuntimeException(ex);  
  49.         }finally{  
  50.               
  51.             try{  
  52.                 if(out!=null)  
  53.                     out.close();  
  54.             }catch(IOException ex){  
  55.                 throw new RuntimeException("关闭Tar输出流出现异常",ex);  
  56.             }finally{  
  57.                 //清理操作   
  58.                 if(!boo && targetTarFile.exists())//归档不成功,   
  59.                     targetTarFile.delete();  
  60.                   
  61.             }  
  62.               
  63.         }  
  64.   
  65.           
  66.           
  67.           
  68.     }  
  69.       
  70.       
  71.     /** 
  72.      * 测试压缩归档tar.gz文件 
  73.      */  
  74.     public void testTarGz(){  
  75.           
  76.         File tarFile = testTar();//生成的tar文件   
  77.           
  78.         File gzFile = new File(tarFile + ".gz");//将要生成的压缩文件   
  79.           
  80.         GZIPOutputStream out = null;  
  81.           
  82.         InputStream in = null;  
  83.           
  84.         boolean boo = false;//是否成功   
  85.           
  86.         try{  
  87.               
  88.             in = new FileInputStream(tarFile);  
  89.               
  90.             out = new GZIPOutputStream(new FileOutputStream(gzFile),1024 * 2);  
  91.               
  92.             byte b[] = new byte[1024 * 2];  
  93.               
  94.             int length = 0;  
  95.               
  96.             while( (length = in.read(b)) != -1 ){  
  97.                   
  98.                 out.write(b,0,length);  
  99.             }  
  100.               
  101.             boo = true;  
  102.               
  103.         }catch(Exception ex){  
  104.               
  105.             throw new RuntimeException("压缩归档文件失败",ex);  
  106.         }finally{  
  107.               
  108.             try{  
  109.                 if(out!=null)  
  110.                     out.close();  
  111.                 if(in!=null)  
  112.                     in.close();  
  113.             }catch(IOException ex){  
  114.                 throw new RuntimeException("关闭流出现异常",ex);  
  115.             }finally{  
  116.                   
  117.                 if(!boo){//清理操作   
  118.                       
  119.                     tarFile.delete();  
  120.                       
  121.                     if(gzFile.exists())  
  122.                         gzFile.delete();  
  123.                       
  124.                 }  
  125.                   
  126.             }  
  127.               
  128.         }  
  129.           
  130.     }  
  131.       
  132.       
  133.       
  134.     /** 
  135.      * 测试解压归档tar文件 
  136.      */  
  137.     public void testUnTar(){  
  138.           
  139.         File srcTarFile = new File("c:/upload.tar");//要解压缩的tar文件对象   
  140.           
  141.         String destDir = "c:/XZou";//把解压的文件放置到c盘下的XZou目录下面   
  142.           
  143.         boolean boo = false;//是否压缩成功   
  144.           
  145.         try {  
  146.             unTar(srcTarFile,destDir);  
  147.             boo = true;  
  148.         } catch (IOException e) {  
  149.             throw new RuntimeException(e);  
  150.         }finally{  
  151.             //清理操作   
  152.             if(!boo)  
  153.                 deleteDirectory(new File(destDir));//目标文件夹 。清理   
  154.               
  155.         }  
  156.           
  157.     }  
  158.       
  159.     /** 
  160.      * 测试解压归档tar文件 
  161.      */  
  162.     public void testUnTarGz(){  
  163.           
  164.         File srcTarGzFile = new File("c:/up.tar.gz");//要解压缩的tar.gz文件对象   
  165.           
  166.         String destDir = "c:/XZou";//把解压的文件放置到c盘下的XZou目录下面   
  167.           
  168.         boolean boo = false;//是否压缩成功   
  169.           
  170.         try {  
  171.             unTarGz(srcTarGzFile,destDir);  
  172.             boo = true;  
  173.         } catch (IOException e) {  
  174.             throw new RuntimeException(e);  
  175.         }finally{  
  176.             //清理操作   
  177.             if(!boo)  
  178.                 deleteDirectory(new File(destDir));//目标文件夹 。清理   
  179.               
  180.         }  
  181.           
  182.     }  
  183.       
  184.     public static void main(String[] args) throws Exception {  
  185.       
  186.         XZouTarAndGz jtar = new XZouTarAndGz();  
  187.           
  188.         //jtar.testTar();   
  189.           
  190.         //jtar.testTarGz();   
  191.           
  192.         //jtar.testUnTar();   
  193.           
  194.         jtar.testUnTarGz();  
  195.           
  196.     }  
  197.     /** 
  198.      * 归档tar文件 
  199.      * @param file 归档的文件对象 
  200.      * @param out 输出tar流 
  201.      * @param dir 相对父目录名称 
  202.      * @param boo 是否把空目录归档进去 
  203.      */  
  204.     public static void tar(File file,TarOutputStream out,String dir,boolean boo) throws IOException{  
  205.           
  206.         if(file.isDirectory()){//是目录   
  207.               
  208.             File []listFile = file.listFiles();//得出目录下所有的文件对象   
  209.               
  210.             if(listFile.length == 0 && boo){//空目录归档   
  211.                   
  212.                 out.putNextEntry(new TarEntry(dir + file.getName() + "/"));//将实体放入输出Tar流中   
  213.                   
  214.                 System.out.println("归档." + dir + file.getName() + "/");  
  215.                   
  216.                 return;  
  217.             }else{  
  218.                   
  219.                 for(File cfile: listFile){  
  220.                       
  221.                     tar(cfile,out,dir + file.getName() + "/",boo);//递归归档   
  222.                 }  
  223.             }  
  224.               
  225.         }else if(file.isFile()){//是文件   
  226.               
  227.             System.out.println("归档." + dir + file.getName() + "/");  
  228.               
  229.             byte[] bt = new byte[2048*2];  
  230.               
  231.             TarEntry ze = new TarEntry(dir+file.getName());//构建tar实体   
  232.             //设置压缩前的文件大小   
  233.             ze.setSize(file.length());  
  234.               
  235.             //ze.setName(file.getName());//设置实体名称.使用默认名称   
  236.               
  237.             out.putNextEntry(ze);将实体放入输出Tar流中   
  238.               
  239.             FileInputStream fis = null;  
  240.               
  241.             try{  
  242.                   
  243.                 fis = new FileInputStream(file);  
  244.                   
  245.                 int i=0;  
  246.                   
  247.                 while((i = fis.read(bt)) != -1) {//循环读出并写入输出Tar流中   
  248.     
  249.                     out.write(bt, 0, i);  
  250.                 }  
  251.   
  252.             }catch(IOException ex){  
  253.                 throw new IOException("写入归档文件出现异常",ex);  
  254.             }finally{  
  255.                   
  256.                 try{  
  257.                     if (fis != null)  
  258.                         fis.close();//关闭输入流   
  259.                     out.closeEntry();  
  260.                 }catch(IOException ex){  
  261.                       
  262.                     throw new IOException("关闭输入流出现异常");  
  263.                 }  
  264.   
  265.             }             
  266.         }  
  267.           
  268.     }  
  269.       
  270.       
  271.     /** 
  272.      * 解压tar File 
  273.      * @param file 要解压的tar文件对象 
  274.      * @param outputDir 要解压到某个指定的目录下 
  275.      * @throws IOException 
  276.      */  
  277.     public void unTar(File file,String outputDir) throws IOException {  
  278.           
  279.           
  280.         TarInputStream tarIn = null;  
  281.           
  282.         try{  
  283.               
  284.             tarIn = new TarInputStream(new FileInputStream(file),1024 * 2);  
  285.               
  286.             createDirectory(outputDir,null);//创建输出目录   
  287.               
  288.             TarEntry entry = null;  
  289.               
  290.             while( (entry = tarIn.getNextEntry()) != null ){  
  291.                   
  292.                 if(entry.isDirectory()){//是目录   
  293.                       
  294.                     createDirectory(outputDir,entry.getName());//创建空目录   
  295.                       
  296.                 }else{//是文件   
  297.                       
  298.                     File tmpFile = new File(outputDir + "/" + entry.getName());  
  299.                       
  300.                     createDirectory(tmpFile.getParent() + "/",null);//创建输出目录   
  301.                       
  302.                     OutputStream out = null;  
  303.                       
  304.                     try{  
  305.                       
  306.                         out = new FileOutputStream(tmpFile);  
  307.                           
  308.                         int length = 0;  
  309.                           
  310.                         byte[] b = new byte[2048];  
  311.                           
  312.                         while((length = tarIn.read(b)) != -1){  
  313.                             out.write(b, 0, length);  
  314.                         }  
  315.                       
  316.                     }catch(IOException ex){  
  317.                         throw ex;  
  318.                     }finally{  
  319.                           
  320.                         if(out!=null)  
  321.                             out.close();  
  322.                     }  
  323.                       
  324.                 }  
  325.             }  
  326.               
  327.         }catch(IOException ex){  
  328.             throw new IOException("解压归档文件出现异常",ex);  
  329.         } finally{  
  330.             try{  
  331.                 if(tarIn != null){  
  332.                     tarIn.close();  
  333.                 }  
  334.             }catch(IOException ex){  
  335.                 throw new IOException("关闭tarFile出现异常",ex);  
  336.             }  
  337.         }  
  338.           
  339.     }  
  340.       
  341.       
  342.     /** 
  343.      * 解压tar.gz 文件 
  344.      * @param file 要解压的tar.gz文件对象 
  345.      * @param outputDir 要解压到某个指定的目录下 
  346.      * @throws IOException 
  347.      */  
  348.     public void unTarGz(File file,String outputDir) throws IOException{  
  349.           
  350.         TarInputStream tarIn = null;  
  351.           
  352.         try{  
  353.               
  354.             tarIn = new TarInputStream(new GZIPInputStream(  
  355.                     new BufferedInputStream(new FileInputStream(file))),  
  356.                     1024 * 2);  
  357.               
  358.             createDirectory(outputDir,null);//创建输出目录   
  359.               
  360.             TarEntry entry = null;  
  361.               
  362.             while( (entry = tarIn.getNextEntry()) != null ){  
  363.                   
  364.                 if(entry.isDirectory()){//是目录   
  365.                       
  366.                     createDirectory(outputDir,entry.getName());//创建空目录   
  367.                       
  368.                 }else{//是文件   
  369.                       
  370.                     File tmpFile = new File(outputDir + "/" + entry.getName());  
  371.                       
  372.                     createDirectory(tmpFile.getParent() + "/",null);//创建输出目录   
  373.                       
  374.                     OutputStream out = null;  
  375.                       
  376.                     try{  
  377.                       
  378.                         out = new FileOutputStream(tmpFile);  
  379.                           
  380.                         int length = 0;  
  381.                           
  382.                         byte[] b = new byte[2048];  
  383.                           
  384.                         while((length = tarIn.read(b)) != -1){  
  385.                             out.write(b, 0, length);  
  386.                         }  
  387.                       
  388.                     }catch(IOException ex){  
  389.                         throw ex;  
  390.                     }finally{  
  391.                           
  392.                         if(out!=null)  
  393.                             out.close();  
  394.                     }  
  395.                       
  396.                 }  
  397.             }  
  398.               
  399.         }catch(IOException ex){  
  400.             throw new IOException("解压归档文件出现异常",ex);  
  401.         } finally{  
  402.             try{  
  403.                 if(tarIn != null){  
  404.                     tarIn.close();  
  405.                 }  
  406.             }catch(IOException ex){  
  407.                 throw new IOException("关闭tarFile出现异常",ex);  
  408.             }  
  409.         }  
  410.           
  411.           
  412.           
  413.     }  
  414.       
  415.     /** 
  416.      * 构建目录 
  417.      * @param outputDir 
  418.      * @param subDir 
  419.      */  
  420.     public void createDirectory(String outputDir,String subDir){  
  421.           
  422.         File file = new File(outputDir);  
  423.           
  424.         if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空   
  425.               
  426.             file = new File(outputDir + "/" + subDir);  
  427.         }  
  428.           
  429.         if(!file.exists()){  
  430.               
  431.             file.mkdirs();  
  432.         }  
  433.           
  434.     }  
  435.       
  436.     /** 
  437.      * 清理文件(目录或文件) 
  438.      * @param file 
  439.      */  
  440.     public void deleteDirectory(File file){  
  441.           
  442.         if(file.isFile()){  
  443.               
  444.             file.delete();//清理文件   
  445.         }else{  
  446.               
  447.             File list[] = file.listFiles();  
  448.               
  449.             if(list!=null){  
  450.               
  451.                 for(File f: list){  
  452.                     deleteDirectory(f);  
  453.                 }  
  454.                 file.delete();//清理目录   
  455.             }  
  456.               
  457.         }  
  458.           
  459.     }  
  460. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值