Java压缩技术的学习(tar增加非递归算法)

http://blog.csdn.net/psyuhen/article/details/9470005

 

 

由于工作的需要,经常要手动去打上线安装包,为了方便,自己写程序去帮助打包。使用过Unix或者Linux的人都基本上都用过tar打包以及gzip压缩,但在Windows下使用得最多的压缩还是RAR和Zip压缩吧

一、        tar打包、解包

在java的JDK中没有原生的tar归档类,需要下载开源的包: commons-compress-1.0.jar,所以

第一步是下载jar包,可以到www.findjar.com搜索并下载。

第二步导入到工程中;忽略

第三步编写源代码,在写代码之前使用介绍一下

  1. //打包归档输出流   
  2. org.apache.commons.compress.archivers.tar.TarArchiveOutputStream  
  3. //解包归档输入流   
  4. org.apache.commons.compress.archivers.tar.TarArchiveInputStream  
  5. //增加打包归档的条目   
  6. void org.apache.commons.compress.archivers.tar.TarArchiveOutputStream.putArchiveEntry(ArchiveEntry arg0)  
  7. //设置归档的模式:   
  8. TarArchiveOutputStream.LONGFILE_GNU和TarArchiveOutputStream.LONGFILE_ERROR和TarArchiveOutputStream.LONGFILE_TRUNCATE  
  9. void org.apache.commons.compress.archivers.tar.TarArchiveOutputStream.setLongFileMode(int longFileMode)  
  10. //获取归档文件中的条目   
  11. TarArchiveEntry org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry() throws IOException  
//打包归档输出流
org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
//解包归档输入流
org.apache.commons.compress.archivers.tar.TarArchiveInputStream
//增加打包归档的条目
void org.apache.commons.compress.archivers.tar.TarArchiveOutputStream.putArchiveEntry(ArchiveEntry arg0)
//设置归档的模式:
TarArchiveOutputStream.LONGFILE_GNU和TarArchiveOutputStream.LONGFILE_ERROR和TarArchiveOutputStream.LONGFILE_TRUNCATE
void org.apache.commons.compress.archivers.tar.TarArchiveOutputStream.setLongFileMode(int longFileMode)
//获取归档文件中的条目
TarArchiveEntry org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry() throws IOException


 

下面是打包的源代码:

  1.         /** 
  2.      * tar 打包 
  3.      * @param source 源文件 
  4.      * @param dest 目标文件 
  5.      */  
  6.     public static void tar(File source){  
  7.         logger.info("开始对源文件["+source.getName()+"]打成tar包");  
  8.         FileOutputStream out = null;  
  9.         TarArchiveOutputStream tarOut = null;  
  10.           
  11.         String parentPath = source.getParent();  
  12.         File dest = new File(parentPath + source.getName() + ".tar");  
  13.         try{  
  14.             out = new FileOutputStream(dest);  
  15.             tarOut = new TarArchiveOutputStream(out);  
  16.             //解决文件名过长   
  17.             tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);  
  18.             tarPack(source, tarOut,"");  
  19.             tarOut.flush();  
  20.             tarOut.close();  
  21.             logger.info("成功把源文件打为tar包,名称为:["+dest.getName()+"]");  
  22.         }catch (Exception e) {  
  23.             logger.error(e.getMessage(),e);  
  24.         }finally{  
  25.             try{  
  26.                 if(out != null){  
  27.                     out.close();  
  28.                 }  
  29.             }catch (Exception e) {  
  30.                 logger.error(e.getMessage(),e);  
  31.             }  
  32.             try{  
  33.                 if(tarOut != null){  
  34.                     tarOut.close();  
  35.                 }  
  36.             }catch (Exception e) {  
  37.                 logger.error(e.getMessage(),e);  
  38.             }  
  39.         }  
  40.     }  
  41.     /** 
  42.      * 归档 
  43.      * @param source 源文件或者目录 
  44.      * @param tarOut 归档流 
  45.      * @param parentPath 归档后的目录或者文件路径 
  46.      */  
  47.     public static void tarPack(File source,TarArchiveOutputStream tarOut,String parentPath){  
  48.         if(source.isDirectory()){  
  49.             tarDir(source,tarOut,parentPath);  
  50.         }else if(source.isFile()){  
  51.             tarFile(source,tarOut,parentPath);  
  52.         }  
  53.     }  
  54.     /** 
  55.      * 归档文件(非目录) 
  56.      * @param source 源文件 
  57.      * @param tarOut 归档流 
  58.      * @param parentPath 归档后的路径  
  59.      */  
  60.     public static void tarFile(File source,TarArchiveOutputStream tarOut,String parentPath){  
  61.         TarArchiveEntry entry = new TarArchiveEntry(parentPath + source.getName());  
  62.         BufferedInputStream bis = null;  
  63.         FileInputStream fis = null;  
  64.         try {  
  65.             entry.setSize(source.length());  
  66.             tarOut.putArchiveEntry(entry);  
  67.             fis = new FileInputStream(source);  
  68.             bis = new BufferedInputStream(fis);  
  69.             int count = -1;  
  70.             byte []buffer = new byte[1024];  
  71.             while((count = bis.read(buffer, 01024)) != -1){  
  72.                 tarOut.write(buffer, 0, count);  
  73.             }  
  74.             bis.close();  
  75.             tarOut.closeArchiveEntry();  
  76.         } catch (IOException e) {  
  77.             logger.error(e.getMessage(),e);  
  78.         }finally{  
  79.             try {  
  80.                 if(bis != null){  
  81.                     bis.close();  
  82.                 }  
  83.             } catch (Exception e2) {  
  84.                 e2.printStackTrace();  
  85.             }  
  86.             try {  
  87.                 if(fis != null){  
  88.                     fis.close();  
  89.                 }  
  90.             } catch (Exception e2) {  
  91.                 e2.printStackTrace();  
  92.             }  
  93.         }  
  94.     }  
  95.     /** 
  96.      * 归档目录 
  97.      * @param sourceDir 原目录 
  98.      * @param tarOut 归档流 
  99.      * @param parentPath 归档后的父目录 
  100.      */  
  101.     public static void tarDir(File sourceDir,TarArchiveOutputStream tarOut,String parentPath){  
  102.         //归档空目录   
  103.         if(sourceDir.listFiles().length < 1){  
  104.             TarArchiveEntry entry = new TarArchiveEntry(parentPath + sourceDir.getName() + "\\");  
  105.             try {  
  106.                 tarOut.putArchiveEntry(entry);  
  107.                 tarOut.closeArchiveEntry();  
  108.             } catch (IOException e) {  
  109.                 logger.error(e.getMessage(),e);  
  110.             }  
  111.         }  
  112.         //递归 归档   
  113.         for (File file : sourceDir.listFiles()) {  
  114.             tarPack(file, tarOut,parentPath + sourceDir.getName() + "\\");  
  115.         }  
  116.     }  
        /**
	 * tar 打包
	 * @param source 源文件
	 * @param dest 目标文件
	 */
	public static void tar(File source){
		logger.info("开始对源文件["+source.getName()+"]打成tar包");
		FileOutputStream out = null;
		TarArchiveOutputStream tarOut = null;
		
		String parentPath = source.getParent();
		File dest = new File(parentPath + source.getName() + ".tar");
		try{
			out = new FileOutputStream(dest);
			tarOut = new TarArchiveOutputStream(out);
			//解决文件名过长
			tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
			tarPack(source, tarOut,"");
			tarOut.flush();
			tarOut.close();
			logger.info("成功把源文件打为tar包,名称为:["+dest.getName()+"]");
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			try{
				if(out != null){
					out.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(tarOut != null){
					tarOut.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
	}
	/**
	 * 归档
	 * @param source 源文件或者目录
	 * @param tarOut 归档流
	 * @param parentPath 归档后的目录或者文件路径
	 */
	public static void tarPack(File source,TarArchiveOutputStream tarOut,String parentPath){
		if(source.isDirectory()){
			tarDir(source,tarOut,parentPath);
		}else if(source.isFile()){
			tarFile(source,tarOut,parentPath);
		}
	}
	/**
	 * 归档文件(非目录)
	 * @param source 源文件
	 * @param tarOut 归档流
	 * @param parentPath 归档后的路径 
	 */
	public static void tarFile(File source,TarArchiveOutputStream tarOut,String parentPath){
		TarArchiveEntry entry = new TarArchiveEntry(parentPath + source.getName());
		BufferedInputStream bis = null;
		FileInputStream fis = null;
		try {
			entry.setSize(source.length());
			tarOut.putArchiveEntry(entry);
			fis = new FileInputStream(source);
			bis = new BufferedInputStream(fis);
			int count = -1;
			byte []buffer = new byte[1024];
			while((count = bis.read(buffer, 0, 1024)) != -1){
				tarOut.write(buffer, 0, count);
			}
			bis.close();
			tarOut.closeArchiveEntry();
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}finally{
			try {
				if(bis != null){
					bis.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			try {
				if(fis != null){
					fis.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	/**
	 * 归档目录
	 * @param sourceDir 原目录
	 * @param tarOut 归档流
	 * @param parentPath 归档后的父目录
	 */
	public static void tarDir(File sourceDir,TarArchiveOutputStream tarOut,String parentPath){
		//归档空目录
		if(sourceDir.listFiles().length < 1){
			TarArchiveEntry entry = new TarArchiveEntry(parentPath + sourceDir.getName() + "\\");
			try {
				tarOut.putArchiveEntry(entry);
				tarOut.closeArchiveEntry();
			} catch (IOException e) {
				logger.error(e.getMessage(),e);
			}
		}
		//递归 归档
		for (File file : sourceDir.listFiles()) {
			tarPack(file, tarOut,parentPath + sourceDir.getName() + "\\");
		}
	}


 

以下解包的源代码

  1. /** 
  2.      * 解归档 
  3.      * @param source 源归档tar文件 
  4.      */  
  5.     public static void untar(File source){  
  6.         TarArchiveInputStream tarIn = null;  
  7.         FileInputStream fis = null;  
  8.         String parentPath = source.getParent();  
  9.           
  10.         BufferedOutputStream bos = null;  
  11.         FileOutputStream fos = null;  
  12.         try{  
  13.             fis = new FileInputStream(source);  
  14.             tarIn = new TarArchiveInputStream(fis);  
  15.             TarArchiveEntry entry = null;  
  16.             while((entry = tarIn.getNextTarEntry()) != null){  
  17.                 File file = new File(parentPath + "\\" + entry.getName());  
  18.               //为解决空目录   
  19.               if(entry.isDirectory()){  
  20.                     file.mkdirs();  
  21.                     continue;  
  22.                 }  
  23.                 File parentDir = file.getParentFile();  
  24.                 if(!parentDir.exists()){  
  25.                     parentDir.mkdirs();  
  26.                 }  
  27.                   
  28.                 fos = new FileOutputStream(file);  
  29.                 bos = new BufferedOutputStream(fos);  
  30.                 int count = -1;  
  31.                 byte []buffer = new byte[1024];  
  32.                 while((count = tarIn.read(buffer, 0, buffer.length)) != -1){  
  33.                     bos.write(buffer, 0, count);  
  34.                 }  
  35.                 bos.flush();  
  36.                 bos.close();  
  37.                 fos.close();  
  38.             }  
  39.         }catch (Exception e) {  
  40.             logger.error(e.getMessage(),e);  
  41.         }finally{  
  42.             try{  
  43.                 if(fis != null){  
  44.                     fis.close();  
  45.                 }  
  46.             }catch (Exception e) {  
  47.                 logger.error(e.getMessage(),e);  
  48.             }  
  49.             try{  
  50.                 if(fos != null){  
  51.                     fos.close();  
  52.                 }  
  53.             }catch (Exception e) {  
  54.                 logger.error(e.getMessage(),e);  
  55.             }  
  56.             try{  
  57.                 if(bos != null){  
  58.                     bos.close();  
  59.                 }  
  60.             }catch (Exception e) {  
  61.                 logger.error(e.getMessage(),e);  
  62.             }  
  63.             try{  
  64.                 if(tarIn != null){  
  65.                     tarIn.close();  
  66.                 }  
  67.             }catch (Exception e) {  
  68.                 logger.error(e.getMessage(),e);  
  69.             }  
  70.         }  
  71.     }  
/**
	 * 解归档
	 * @param source 源归档tar文件
	 */
	public static void untar(File source){
		TarArchiveInputStream tarIn = null;
		FileInputStream fis = null;
		String parentPath = source.getParent();
		
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		try{
			fis = new FileInputStream(source);
			tarIn = new TarArchiveInputStream(fis);
			TarArchiveEntry entry = null;
			while((entry = tarIn.getNextTarEntry()) != null){
				File file = new File(parentPath + "\\" + entry.getName());
              //为解决空目录
              if(entry.isDirectory()){
					file.mkdirs();
					continue;
				}
				File parentDir = file.getParentFile();
				if(!parentDir.exists()){
					parentDir.mkdirs();
				}
				
				fos = new FileOutputStream(file);
				bos = new BufferedOutputStream(fos);
				int count = -1;
				byte []buffer = new byte[1024];
				while((count = tarIn.read(buffer, 0, buffer.length)) != -1){
					bos.write(buffer, 0, count);
				}
				bos.flush();
				bos.close();
				fos.close();
			}
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			try{
				if(fis != null){
					fis.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(fos != null){
					fos.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(bos != null){
					bos.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(tarIn != null){
					tarIn.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
	}


 Tar的非递归算法:

  1. /** 
  2.      * tar 打包(非递归) 
  3.      * 
  4.      * @param source 源文件 
  5.      * @param dest 目标文件 
  6.      */  
  7.     public static void tarNonRecursion(File source) {  
  8.         logger.info("开始对源文件[" + source.getName() + "]打成tar包");  
  9.         FileOutputStream out = null;  
  10.         TarArchiveOutputStream tarOut = null;  
  11.   
  12.         String parentPath = source.getParent();  
  13.         File dest = new File(parentPath + "/" + source.getName() + ".tar");  
  14.         try {  
  15.             out = new FileOutputStream(dest);  
  16.             tarOut = new TarArchiveOutputStream(out, "GBK");  
  17.             //解决文件名过长   
  18.             tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);  
  19.             Stack<File> fileStack = new Stack<File>();  
  20.             fileStack.push(source);  
  21.             File curFile;  
  22.             File preFile = null;  
  23.             while (!fileStack.empty()) {  
  24.                 curFile = fileStack.peek();  
  25.                 File[] fileLists = curFile.listFiles();  
  26.                 if (curFile.isFile()  
  27.                         || (preFile != null && (preFile.getParent().equals(curFile.getAbsolutePath())))  
  28.                         || (fileLists.length == 0)) {  
  29.                     File popFile = fileStack.pop();  
  30.                     String filePath = popFile.getAbsolutePath();  
  31.                     filePath = filePath.replaceAll("[\\\\]""/");  
  32.                     filePath = filePath.substring(parentPath.length() + 1);  
  33.                     preFile = curFile;  
  34.                     if (popFile.isFile()) {  
  35.                         filePath = filePath.substring(0, filePath.lastIndexOf("/"));  
  36.                         tarFile(popFile, tarOut, filePath + "/");  
  37.                     } else {  
  38.                         TarArchiveEntry entry = new TarArchiveEntry(filePath + "/");  
  39.                         try {  
  40.                             tarOut.putArchiveEntry(entry);  
  41.                             tarOut.closeArchiveEntry();  
  42.                         } catch (IOException e) {  
  43.                             logger.error(e.getMessage(), e);  
  44.                         }  
  45.                     }  
  46.                 } else {  
  47.                     for (File file : fileLists) {  
  48.                         fileStack.push(file);  
  49.                     }  
  50.                 }  
  51.             }  
  52.             tarOut.flush();  
  53.             tarOut.close();  
  54.             logger.info("成功把源文件打为tar包,名称为:[" + dest.getName() + "]");  
  55.         } catch (Exception e) {  
  56.             logger.error(e.getMessage(), e);  
  57.         } finally {  
  58.             try {  
  59.                 if (out != null) {  
  60.                     out.close();  
  61.                 }  
  62.             } catch (Exception e) {  
  63.                 logger.error(e.getMessage(), e);  
  64.             }  
  65.             try {  
  66.                 if (tarOut != null) {  
  67.                     tarOut.close();  
  68.                 }  
  69.             } catch (Exception e) {  
  70.                 logger.error(e.getMessage(), e);  
  71.             }  
  72.         }  
  73.     }  
/**
     * tar 打包(非递归)
     *
     * @param source 源文件
     * @param dest 目标文件
     */
    public static void tarNonRecursion(File source) {
        logger.info("开始对源文件[" + source.getName() + "]打成tar包");
        FileOutputStream out = null;
        TarArchiveOutputStream tarOut = null;

        String parentPath = source.getParent();
        File dest = new File(parentPath + "/" + source.getName() + ".tar");
        try {
            out = new FileOutputStream(dest);
            tarOut = new TarArchiveOutputStream(out, "GBK");
            //解决文件名过长
            tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
            Stack<File> fileStack = new Stack<File>();
            fileStack.push(source);
            File curFile;
            File preFile = null;
            while (!fileStack.empty()) {
                curFile = fileStack.peek();
                File[] fileLists = curFile.listFiles();
                if (curFile.isFile()
                        || (preFile != null && (preFile.getParent().equals(curFile.getAbsolutePath())))
                        || (fileLists.length == 0)) {
                    File popFile = fileStack.pop();
                    String filePath = popFile.getAbsolutePath();
                    filePath = filePath.replaceAll("[\\\\]", "/");
                    filePath = filePath.substring(parentPath.length() + 1);
                    preFile = curFile;
                    if (popFile.isFile()) {
                        filePath = filePath.substring(0, filePath.lastIndexOf("/"));
                        tarFile(popFile, tarOut, filePath + "/");
                    } else {
                        TarArchiveEntry entry = new TarArchiveEntry(filePath + "/");
                        try {
                            tarOut.putArchiveEntry(entry);
                            tarOut.closeArchiveEntry();
                        } catch (IOException e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                } else {
                    for (File file : fileLists) {
                        fileStack.push(file);
                    }
                }
            }
            tarOut.flush();
            tarOut.close();
            logger.info("成功把源文件打为tar包,名称为:[" + dest.getName() + "]");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            try {
                if (tarOut != null) {
                    tarOut.close();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }


 

二、        gzip压缩、解压

注意gzip不支持压缩目录的;Jdk里提供了类支持压缩文件;默认生成.gz文件

主要对应的Java类为:

  1. //Gzip输入流   
  2. java.util.zip.GZIPInputStream  
  3. //Gzip输出流   
  4. java.util.zip.GZIPOutputStream  
//Gzip输入流
java.util.zip.GZIPInputStream
//Gzip输出流
java.util.zip.GZIPOutputStream


 

压缩源代码

  1. /** 
  2.      * gzip 压缩,跟源文件在相同目录中生成.gz文件 
  3.      * @param source 源文件 
  4.      */  
  5.     public static void gzip(File source){  
  6.         logger.info("开始对源文件["+source.getName()+"]压缩成.gz包");  
  7.         String dir = source.getParent();  
  8.         File target = new File(dir + "\\" +source.getName() + ".gz");  
  9.         FileInputStream fis = null;  
  10.         FileOutputStream fos = null;  
  11.         GZIPOutputStream gzipOS = null;  
  12.         try{  
  13.             fis = new FileInputStream(source);  
  14.             fos = new FileOutputStream(target);  
  15.             gzipOS = new GZIPOutputStream(fos);  
  16.             int count = -1;  
  17.             byte [] buffer = new byte[1024];  
  18.             while((count = fis.read(buffer, 0, buffer.length)) != -1){  
  19.                 gzipOS.write(buffer, 0, count);  
  20.             }  
  21.             gzipOS.flush();  
  22.             gzipOS.close();  
  23.             logger.info("成功把源文件["+source.getName()+"]压缩为.gz包["+target.getName()+"]");  
  24.         }catch (Exception e) {  
  25.             logger.error(e.getMessage(),e);  
  26.         }finally{  
  27.             try{  
  28.                 if(fis!=null){  
  29.                     fis.close();  
  30.                 }  
  31.             }catch (Exception e) {  
  32.                 logger.error(e.getMessage(),e);  
  33.             }  
  34.             try{  
  35.                 if(fos!=null){  
  36.                     fos.close();  
  37.                 }  
  38.             }catch (Exception e) {  
  39.                 logger.error(e.getMessage(),e);  
  40.             }  
  41.             try{  
  42.                 if(gzipOS!=null){  
  43.                     gzipOS.close();  
  44.                 }  
  45.             }catch (Exception e) {  
  46.                 logger.error(e.getMessage(),e);  
  47.             }  
  48.         }  
  49.     }  
/**
	 * gzip 压缩,跟源文件在相同目录中生成.gz文件
	 * @param source 源文件
	 */
	public static void gzip(File source){
		logger.info("开始对源文件["+source.getName()+"]压缩成.gz包");
		String dir = source.getParent();
		File target = new File(dir + "\\" +source.getName() + ".gz");
		FileInputStream fis = null;
		FileOutputStream fos = null;
		GZIPOutputStream gzipOS = null;
		try{
			fis = new FileInputStream(source);
			fos = new FileOutputStream(target);
			gzipOS = new GZIPOutputStream(fos);
			int count = -1;
			byte [] buffer = new byte[1024];
			while((count = fis.read(buffer, 0, buffer.length)) != -1){
				gzipOS.write(buffer, 0, count);
			}
			gzipOS.flush();
			gzipOS.close();
			logger.info("成功把源文件["+source.getName()+"]压缩为.gz包["+target.getName()+"]");
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			try{
				if(fis!=null){
					fis.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(fos!=null){
					fos.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(gzipOS!=null){
					gzipOS.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
	}


 

解压.gz包源代码

  1. /** 
  2.      * 解压.gz包 
  3.      * @param source 源.gz包 
  4.      */  
  5.     public static void ungzip(File source){  
  6.         GZIPInputStream gzipIS = null;  
  7.         FileInputStream fis = null;  
  8.         FileOutputStream fos = null;  
  9.         BufferedOutputStream bos = null;  
  10.           
  11.         String fileName = source.getName();  
  12.         fileName = fileName.substring(0, fileName.lastIndexOf("."));  
  13.         try{  
  14.             fis = new FileInputStream(source);  
  15.             gzipIS = new GZIPInputStream(fis);  
  16.             File target = new File(source.getParent() + "\\" + fileName);  
  17.             fos = new FileOutputStream(target);  
  18.             bos = new BufferedOutputStream(fos);  
  19.               
  20.             int count = -1;  
  21.             byte []buffer = new byte[1024];  
  22.             while((count = gzipIS.read(buffer, 0, buffer.length)) != -1){  
  23.                 bos.write(buffer, 0, count);  
  24.             }  
  25.             bos.flush();  
  26.         }catch (Exception e) {  
  27.             logger.error(e.getMessage(),e);  
  28.         }finally{  
  29.             try{  
  30.                 if(fis!=null){  
  31.                     fis.close();  
  32.                 }  
  33.             }catch (Exception e) {  
  34.                 logger.error(e.getMessage(),e);  
  35.             }  
  36.             try{  
  37.                 if(fos!=null){  
  38.                     fos.close();  
  39.                 }  
  40.             }catch (Exception e) {  
  41.                 logger.error(e.getMessage(),e);  
  42.             }  
  43.             try{  
  44.                 if(bos != null){  
  45.                     bos.close();  
  46.                 }  
  47.             }catch (Exception e) {  
  48.                 logger.error(e.getMessage(),e);  
  49.             }  
  50.             try{  
  51.                 if(gzipIS!=null){  
  52.                     gzipIS.close();  
  53.                 }  
  54.             }catch (Exception e) {  
  55.                 logger.error(e.getMessage(),e);  
  56.             }  
  57.         }  
  58.     }  
/**
	 * 解压.gz包
	 * @param source 源.gz包
	 */
	public static void ungzip(File source){
		GZIPInputStream gzipIS = null;
		FileInputStream fis = null;
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		
		String fileName = source.getName();
		fileName = fileName.substring(0, fileName.lastIndexOf("."));
		try{
			fis = new FileInputStream(source);
			gzipIS = new GZIPInputStream(fis);
			File target = new File(source.getParent() + "\\" + fileName);
			fos = new FileOutputStream(target);
			bos = new BufferedOutputStream(fos);
			
			int count = -1;
			byte []buffer = new byte[1024];
			while((count = gzipIS.read(buffer, 0, buffer.length)) != -1){
				bos.write(buffer, 0, count);
			}
			bos.flush();
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			try{
				if(fis!=null){
					fis.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(fos!=null){
					fos.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(bos != null){
					bos.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			try{
				if(gzipIS!=null){
					gzipIS.close();
				}
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
	}


 

 

三、        zip压缩、解压

Jdk提供代码技术支持,tar打包跟zip压缩类似的。

在Jdk中主要的类为:

  1. java.util.zip.ZipOutputStream  
  2. java.util.zip.ZipInputStream  
java.util.zip.ZipOutputStream
java.util.zip.ZipInputStream

 

压缩源代码

  1. /** 
  2.      * 使用zip压缩文件 
  3.      * @param source 源文件或者文件夹 
  4.      */  
  5.     public static void zip(File source){  
  6.         String dir = source.getParent();  
  7.         File target = new File(dir + "\\" +source.getName() + ".zip");  
  8.         FileOutputStream fos = null;  
  9.         ZipOutputStream zipos = null;  
  10.           
  11.         try{  
  12.             fos = new FileOutputStream(target);  
  13.             zipos = new ZipOutputStream(fos);  
  14.             zipFile(source, zipos, "");  
  15.             //必须要下面一步,否则会报no such file or directory错误   
  16.             zipos.close();  
  17.         }catch (Exception e) {  
  18.             logger.error(e.getMessage(),e);  
  19.         }finally{  
  20.             try {  
  21.                 if(fos != null){  
  22.                     fos.close();  
  23.                 }  
  24.             } catch (Exception e2) {  
  25.                 e2.printStackTrace();  
  26.             }  
  27.             try {  
  28.                 if(zipos != null){  
  29.                     zipos.close();  
  30.                 }  
  31.             } catch (Exception e2) {  
  32.                 e2.printStackTrace();  
  33.             }  
  34.         }  
  35.     }  
  36.     /** 
  37.      * 递归压缩文件或者文件夹 
  38.      * @param source 源文件 
  39.      * @param zipos zip输出流 
  40.      * @param parentPath 路径  
  41.      */  
  42.     public static void zipFile(File source,ZipOutputStream zipos,String parentPath){  
  43.         FileInputStream fis = null;  
  44.         BufferedInputStream bis = null;  
  45.         try {  
  46.             //增加目录    
  47.             if(source.isDirectory()){  
  48.                 File[]files = source.listFiles();  
  49.                 if(files.length < 1){  
  50.                     ZipEntry entry = new ZipEntry(parentPath + source.getName()  + "/");  
  51.                     zipos.putNextEntry(entry);  
  52.                 }  
  53.                 for (File file : files) {  
  54.                     zipFile(file, zipos, parentPath + source.getName() + "/");  
  55.                 }  
  56.             }else if(source.isFile()){  
  57.                 fis = new FileInputStream(source);  
  58.                 bis = new BufferedInputStream(fis);  
  59.                 ZipEntry entry = new ZipEntry(parentPath + source.getName());  
  60.                 zipos.putNextEntry(entry);  
  61.                 int count = -1;  
  62.                 byte []buffer = new byte[1024];  
  63.                 while((count = bis.read(buffer, 0, buffer.length)) != -1){  
  64.                     zipos.write(buffer, 0, count);  
  65.                 }  
  66.                 fis.close();  
  67.                 bis.close();  
  68.             }  
  69.         } catch (IOException e) {  
  70.             logger.error(e.getMessage(),e);  
  71.         }finally{  
  72.             try {  
  73.                 if(bis != null){  
  74.                     bis.close();  
  75.                 }  
  76.             } catch (Exception e2) {  
  77.                 e2.printStackTrace();  
  78.             }  
  79.             try {  
  80.                 if(fis != null){  
  81.                     fis.close();  
  82.                 }  
  83.             } catch (Exception e2) {  
  84.                 e2.printStackTrace();  
  85.             }  
  86.         }  
  87.     }  
/**
	 * 使用zip压缩文件
	 * @param source 源文件或者文件夹
	 */
	public static void zip(File source){
		String dir = source.getParent();
		File target = new File(dir + "\\" +source.getName() + ".zip");
		FileOutputStream fos = null;
		ZipOutputStream zipos = null;
		
		try{
			fos = new FileOutputStream(target);
			zipos = new ZipOutputStream(fos);
			zipFile(source, zipos, "");
			//必须要下面一步,否则会报no such file or directory错误
			zipos.close();
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			try {
				if(fos != null){
					fos.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			try {
				if(zipos != null){
					zipos.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	/**
	 * 递归压缩文件或者文件夹
	 * @param source 源文件
	 * @param zipos zip输出流
	 * @param parentPath 路径 
	 */
	public static void zipFile(File source,ZipOutputStream zipos,String parentPath){
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try {
			//增加目录 
			if(source.isDirectory()){
				File[]files = source.listFiles();
				if(files.length < 1){
					ZipEntry entry = new ZipEntry(parentPath + source.getName()  + "/");
					zipos.putNextEntry(entry);
				}
				for (File file : files) {
					zipFile(file, zipos, parentPath + source.getName() + "/");
				}
			}else if(source.isFile()){
				fis = new FileInputStream(source);
				bis = new BufferedInputStream(fis);
				ZipEntry entry = new ZipEntry(parentPath + source.getName());
				zipos.putNextEntry(entry);
				int count = -1;
				byte []buffer = new byte[1024];
				while((count = bis.read(buffer, 0, buffer.length)) != -1){
					zipos.write(buffer, 0, count);
				}
				fis.close();
				bis.close();
			}
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}finally{
			try {
				if(bis != null){
					bis.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			try {
				if(fis != null){
					fis.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}


 

解压源代码

  1. /** 
  2.      * 解压zip文件 
  3.      * @param source 源.zip文件 
  4.      */  
  5.     public static void unzip(File source){  
  6.         ZipInputStream zipIn = null;  
  7.         FileInputStream fis = null;  
  8.         String parentPath = source.getParent();  
  9.           
  10.         System.out.println(parentPath);  
  11.         BufferedOutputStream bos = null;  
  12.         FileOutputStream fos = null;  
  13.         try{  
  14.             fis = new FileInputStream(source);  
  15.             zipIn = new ZipInputStream(fis);  
  16.             ZipEntry entry = null;  
  17.             while((entry = zipIn.getNextEntry()) != null){  
  18.                 File file = new File(parentPath + "\\" + entry.getName());  
  19.                   
  20.                 //为了空目录的出现   
  21.                 if(entry.isDirectory()){  
  22.                     file.mkdirs();  
  23.                     continue;  
  24.                 }  
  25.                   
  26.                 File parentDir = file.getParentFile();  
  27.                 if(!parentDir.exists()){  
  28.                     parentDir.mkdirs();  
  29.                 }  
  30.                 fos = new FileOutputStream(file);  
  31.                 bos = new BufferedOutputStream(fos);  
  32.                 int count = -1;  
  33.                 byte []buffer = new byte[1024];  
  34.                 while((count = zipIn.read(buffer, 0, buffer.length)) != -1){  
  35.                     bos.write(buffer, 0, count);  
  36.                 }  
  37.                 bos.flush();  
  38.                 bos.close();  
  39.                 fos.close();  
  40.             }  
  41.             zipIn.close();  
  42.         }catch (Exception e) {  
  43.             logger.error(e.getMessage(),e);  
  44.         }finally{  
  45.             try{  
  46.                 if(fis != null){  
  47.                     fis.close();  
  48.                 }  
  49.             }catch (Exception e) {  
  50.                 logger.error(e.getMessage(),e);  
  51.             }  
  52.             try{  
  53.                 if(fos != null){  
  54.                     fos.close();  
  55.                 }  
  56.             }catch (Exception e) {  
  57.                 logger.error(e.getMessage(),e);  
  58.             }  
  59.             try{  
  60.                 if(bos != null){  
  61.                     bos.close();  
  62.                 }  
  63.             }catch (Exception e) {  
  64.                 logger.error(e.getMessage(),e);  
  65.             }  
  66.             try{  
  67.                 if(zipIn != null){  
  68.                     zipIn.close();  
  69.                 }  
  70.             }catch (Exception e) {  
  71.                 logger.error(e.getMessage(),e);  
  72.             }  
  73.         }  
  74.     }  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值