Java的tar打包和gzip压缩(增加非递归算法)

4 篇文章 0 订阅

以下tar打包:参考了网上的资料,非真正原创

 

/**
	 * tar 打包
	 * @param source 源文件
	 * @param dest 目标文件
	 */
	public static void tar(File source,File dest){
		logger.info("开始对源文件["+source.getName()+"]打成tar包");
		FileOutputStream out = null;
		TarArchiveOutputStream tarOut = null;

		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) {
			e.printStackTrace();
		}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) {
				e.printStackTrace();
			}
		}
		//递归 归档
		for (File file : sourceDir.listFiles()) {
			tarPack(file, tarOut,parentPath + sourceDir.getName() + "\\");
		}
	}


以下为gzip压缩原代码

 

/**
	 * gzip 压缩,跟源文件在相同目录中生成.gz文件
	 * @param source 源文件
	 */
	public static void gzip(File source){
		logger.info("开始对源文件["+source.getName()+"]压缩成.gz包");
		String sourcePath = source.getAbsolutePath();
		int lastIndexOf = sourcePath.lastIndexOf("\\");
		String dir = sourcePath.substring(0, lastIndexOf);
		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) {
			e.printStackTrace();
		}finally{
			try{
				if(fis!=null){
					fis.close();
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
			try{
				if(fos!=null){
					fos.close();
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
			try{
				if(gzipOS!=null){
					gzipOS.close();
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


 

 

Tar的非递归算法:

 

/**
     * 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);
            }
        }
    }


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

psyuhen

你的鼓励是我最大的动力谢谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值