博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java中的Gzip进行多文件的保存
阅读量:4091 次
发布时间:2019-05-25

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

/** * 通过JDK原生的GZIP压缩和解压缩文件 * @date 2017年12月29日  * @version V1.0 */public class GzipUtils {    public static byte[] gzip(byte[] data) throws Exception{    	ByteArrayOutputStream bos = new ByteArrayOutputStream();    	GZIPOutputStream gzip = new GZIPOutputStream(bos);    	gzip.write(data);    	gzip.finish();    	gzip.close();    	byte[] ret = bos.toByteArray();    	bos.close();    	return ret;    }        public static byte[] ungzip(byte[] data) throws Exception{    	ByteArrayInputStream bis = new ByteArrayInputStream(data);    	GZIPInputStream gzip = new GZIPInputStream(bis);    	byte[] buf = new byte[1024];    	int num = -1;    	ByteArrayOutputStream bos = new ByteArrayOutputStream();    	while((num = gzip.read(buf, 0 , buf.length)) != -1 ){    		bos.write(buf, 0, num);    	}    	gzip.close();    	bis.close();    	byte[] ret = bos.toByteArray();    	bos.flush();    	bos.close();    	return ret;    }        public static void main(String[] args) throws Exception{		    	//读取文件    	String readPath = System.getProperty("user.dir") + File.separatorChar + "sources" +  File.separatorChar + "006.jpg";        File file = new File(readPath);        //直接将文件io流一次性读到byte数组中        FileInputStream in = new FileInputStream(file);          byte[] data = new byte[in.available()];          in.read(data);          in.close();                  System.out.println("文件原始大小:" + data.length);        //测试压缩                byte[] ret1 = GzipUtils.gzip(data);        System.out.println("压缩之后大小:" + ret1.length);                byte[] ret2 = GzipUtils.ungzip(ret1);        System.out.println("还原之后大小:" + ret2.length);                //写出文件        String writePath = System.getProperty("user.dir") + File.separatorChar + "receive" +  File.separatorChar + "006.jpg";        FileOutputStream fos = new FileOutputStream(writePath);        //输出流直接输出字节数组        fos.write(ret2);        fos.close();    	    	    		}            }

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

你可能感兴趣的文章
WPF 实现多语言
查看>>
VS2017编译duilib
查看>>
MFC句柄
查看>>
MFC知识点
查看>>
MFC添加右键菜单
查看>>
C++ typedef
查看>>
托管c++编译错误 error LNK2019: 无法解析的外部符号 "public: __thiscall
查看>>
Mutex的使用
查看>>
WPF 利用HwndSource拦截Windows消息
查看>>
Gradle初次使用
查看>>
JDK-Integer源码解读
查看>>
JDK-String源码解读
查看>>
工具集合
查看>>
关于工作中的一些问题的思考
查看>>
selenuim配置
查看>>
工作记录
查看>>
单例设计模式
查看>>
浅谈自己对于spring aop的理解
查看>>
java多线程之锁
查看>>
java多线程之原子类
查看>>