博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java实现多个文件打包tar gz
阅读量:4291 次
发布时间:2019-05-27

本文共 2297 字,大约阅读时间需要 7 分钟。

package test;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.GZIPOutputStream;import org.apache.commons.compress.archivers.tar.TarArchiveEntry;import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;import org.apache.commons.compress.utils.IOUtils;public class DaBao_tar_gz {	/**	 * 	 * @Title: pack	 * @Description: 将一组文件打成tar包	 * @param sources	 *            要打包的原文件数组	 * @param target	 *            打包后的文件	 * @return File 返回打包后的文件	 * @throws	 */	public File pack(File[] sources, File target) {		FileOutputStream out = null;		try {			out = new FileOutputStream(target);		} catch (FileNotFoundException e1) {			e1.printStackTrace();		}		TarArchiveOutputStream os = new TarArchiveOutputStream(out);		for (File file : sources) {			try {				os.putArchiveEntry(new TarArchiveEntry(file));				IOUtils.copy(new FileInputStream(file), os);				os.closeArchiveEntry();			} catch (FileNotFoundException e) {				e.printStackTrace();			} catch (IOException e) {				e.printStackTrace();			}		}		if (os != null) {			try {				os.flush();				os.close();				System.out.println("打包后文件为:" + target);			} catch (IOException e) {				e.printStackTrace();			}		}		return target;	}	/**	 * 	 * @Title: compress	 * @Description: 将文件用gzip压缩	 * @param source	 *            需要压缩的文件	 * @return File 返回压缩后的文件	 * @throws	 */	public File compress(File source) {		File target = new File(source.getName() + ".gz");		FileInputStream in = null;		GZIPOutputStream out = null;		try {			in = new FileInputStream(source);			out = new GZIPOutputStream(new FileOutputStream(target));			byte[] array = new byte[1024];			int number = -1;			while ((number = in.read(array, 0, array.length)) != -1) {				out.write(array, 0, number);			}		} catch (FileNotFoundException e) {			e.printStackTrace();			return null;		} catch (IOException e) {			e.printStackTrace();			return null;		} finally {			if (in != null) {				try {					in.close();				} catch (IOException e) {					e.printStackTrace();					return null;				}			}			if (out != null) {				try {					out.close();					System.out.println("打包后文件为:" + target);				} catch (IOException e) {					e.printStackTrace();					return null;				}			}		}		return target;	}}

转载地址:http://pkegi.baihongyu.com/

你可能感兴趣的文章
3种web会话管理的方式
查看>>
SSM(框架)-异常1:面向接口式编程异常
查看>>
Android蓝牙4.0之玩爆智能穿戴、家具(二)
查看>>
使用Condition实现多线程之间调用
查看>>
javaAPI之String
查看>>
JQ 新窗口打开链接并设置参数
查看>>
JS中常遇到的浏览器兼容问题和解决方法
查看>>
JAVA学习笔记之-servlet知识点
查看>>
apache 配置不同的端口访问不同的站点
查看>>
2017年3月Java9带来的革新!
查看>>
Log4j容器深入探究
查看>>
记glide框架使用中所遇到的问题
查看>>
学习AOP之透过Spring的Ioc理解Advisor
查看>>
Jquery一个简单的注册验证
查看>>
SpringMVC基础_ControllerAdvice
查看>>
Toast还能显示图片你知道么?
查看>>
安卓三状态切换按钮TriStateToggleButton
查看>>
Spring框架-AOP细节
查看>>
java.lang.Instrument 代理Agent使用
查看>>
Javascript:指针、帽子和女朋友
查看>>