Java压缩技术(四) GZIP——Java原生实现

转载自  Java压缩技术(四) GZIP——Java原生实现

GZIP常常用在linxu环境下,是一种非常简单的压缩算法。在Java实现API中,它仅仅包含两个实现类:GZIPInputStream和GZIPOutputStream。 
GZIPOutputStream类用于压缩 
GZIPInputStream类用于解压缩 

先说压缩实现,GZIPOutputStream只有一个方法用于压缩,就是带定长的write方法。简单调用如下文所示: 

Java代码 
  1. /** 
  2.  * 数据压缩 
  3.  *  
  4.  * @param is 
  5.  * @param os 
  6.  * @throws Exception 
  7.  */  
  8. public static void compress(InputStream is, OutputStream os)  
  9.         throws Exception {  
  10.   
  11.     GZIPOutputStream gos = new GZIPOutputStream(os);  
  12.   
  13.     int count;  
  14.     byte data[] = new byte[BUFFER];  
  15.     while ((count = is.read(data, 0, BUFFER)) != -1) {  
  16.         gos.write(data, 0, count);  
  17.     }  
  18.   
  19.     gos.finish();  
  20.   
  21.     gos.flush();  
  22.     gos.close();  
  23. }  

记得完成操作后,调用finish方法和flush方法!
核心的压缩实现就这么多!
对于解压缩,GZIPInputStream也对应GZIPOutputStream提供了一个带定长的read方法。简单调用如下文所示: 
Java代码  
  1. /** 
  2.  * 数据解压缩 
  3.  *  
  4.  * @param is 
  5.  * @param os 
  6.  * @throws Exception 
  7.  */  
  8. public static void decompress(InputStream is, OutputStream os)  
  9.         throws Exception {  
  10.   
  11.     GZIPInputStream gis = new GZIPInputStream(is);  
  12.   
  13.     int count;  
  14.     byte data[] = new byte[BUFFER];  
  15.     while ((count = gis.read(data, 0, BUFFER)) != -1) {  
  16.         os.write(data, 0, count);  
  17.     }  
  18.   
  19.     gis.close();  
  20. }  

就这么简单! 核心内容完毕! 
顺便补充一下,在liunx下操作gzip命令 

gzip file 用于压缩,如 gzip a.txt 将得到文件 a.txt.gz 同时删除文件a.txt!  
gzip -d file.gz 用于解压缩,如 gzip -d a.txt.gz 将得到文件 a.txt 同时删除文件a.txt.gz!  

根据这些特性,我补充了相应的文件操作实现,详见下文!
完整实现: 
Java代码  
  1. /** 
  2.  * 2010-4-13 
  3.  */  
  4. package org.zlex.commons.io;  
  5.   
  6. import java.io.ByteArrayInputStream;  
  7. import java.io.ByteArrayOutputStream;  
  8. import java.io.File;  
  9. import java.io.FileInputStream;  
  10. import java.io.FileOutputStream;  
  11. import java.io.InputStream;  
  12. import java.io.OutputStream;  
  13. import java.util.zip.GZIPInputStream;  
  14. import java.util.zip.GZIPOutputStream;  
  15.   
  16. /** 
  17.  * GZIP工具 
  18.  *  
  19.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
  20.  * @since 1.0 
  21.  */  
  22. public abstract class GZipUtils {  
  23.   
  24.     public static final int BUFFER = 1024;  
  25.     public static final String EXT = ".gz";  
  26.   
  27.     /** 
  28.      * 数据压缩 
  29.      *  
  30.      * @param data 
  31.      * @return 
  32.      * @throws Exception 
  33.      */  
  34.     public static byte[] compress(byte[] data) throws Exception {  
  35.         ByteArrayInputStream bais = new ByteArrayInputStream(data);  
  36.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  37.   
  38.         // 压缩  
  39.         compress(bais, baos);  
  40.   
  41.         byte[] output = baos.toByteArray();  
  42.   
  43.         baos.flush();  
  44.         baos.close();  
  45.   
  46.         bais.close();  
  47.   
  48.         return output;  
  49.     }  
  50.   
  51.     /** 
  52.      * 文件压缩 
  53.      *  
  54.      * @param file 
  55.      * @throws Exception 
  56.      */  
  57.     public static void compress(File file) throws Exception {  
  58.         compress(file, true);  
  59.     }  
  60.   
  61.     /** 
  62.      * 文件压缩 
  63.      *  
  64.      * @param file 
  65.      * @param delete 
  66.      *            是否删除原始文件 
  67.      * @throws Exception 
  68.      */  
  69.     public static void compress(File file, boolean delete) throws Exception {  
  70.         FileInputStream fis = new FileInputStream(file);  
  71.         FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);  
  72.   
  73.         compress(fis, fos);  
  74.   
  75.         fis.close();  
  76.         fos.flush();  
  77.         fos.close();  
  78.   
  79.         if (delete) {  
  80.             file.delete();  
  81.         }  
  82.     }  
  83.   
  84.     /** 
  85.      * 数据压缩 
  86.      *  
  87.      * @param is 
  88.      * @param os 
  89.      * @throws Exception 
  90.      */  
  91.     public static void compress(InputStream is, OutputStream os)  
  92.             throws Exception {  
  93.   
  94.         GZIPOutputStream gos = new GZIPOutputStream(os);  
  95.   
  96.         int count;  
  97.         byte data[] = new byte[BUFFER];  
  98.         while ((count = is.read(data, 0, BUFFER)) != -1) {  
  99.             gos.write(data, 0, count);  
  100.         }  
  101.   
  102.         gos.finish();  
  103.   
  104.         gos.flush();  
  105.         gos.close();  
  106.     }  
  107.   
  108.     /** 
  109.      * 文件压缩 
  110.      *  
  111.      * @param path 
  112.      * @throws Exception 
  113.      */  
  114.     public static void compress(String path) throws Exception {  
  115.         compress(path, true);  
  116.     }  
  117.   
  118.     /** 
  119.      * 文件压缩 
  120.      *  
  121.      * @param path 
  122.      * @param delete 
  123.      *            是否删除原始文件 
  124.      * @throws Exception 
  125.      */  
  126.     public static void compress(String path, boolean delete) throws Exception {  
  127.         File file = new File(path);  
  128.         compress(file, delete);  
  129.     }  
  130.   
  131.     /** 
  132.      * 数据解压缩 
  133.      *  
  134.      * @param data 
  135.      * @return 
  136.      * @throws Exception 
  137.      */  
  138.     public static byte[] decompress(byte[] data) throws Exception {  
  139.         ByteArrayInputStream bais = new ByteArrayInputStream(data);  
  140.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  141.   
  142.         // 解压缩  
  143.   
  144.         decompress(bais, baos);  
  145.   
  146.         data = baos.toByteArray();  
  147.   
  148.         baos.flush();  
  149.         baos.close();  
  150.   
  151.         bais.close();  
  152.   
  153.         return data;  
  154.     }  
  155.   
  156.     /** 
  157.      * 文件解压缩 
  158.      *  
  159.      * @param file 
  160.      * @throws Exception 
  161.      */  
  162.     public static void decompress(File file) throws Exception {  
  163.         decompress(file, true);  
  164.     }  
  165.   
  166.     /** 
  167.      * 文件解压缩 
  168.      *  
  169.      * @param file 
  170.      * @param delete 
  171.      *            是否删除原始文件 
  172.      * @throws Exception 
  173.      */  
  174.     public static void decompress(File file, boolean delete) throws Exception {  
  175.         FileInputStream fis = new FileInputStream(file);  
  176.         FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT,  
  177.                 ""));  
  178.         decompress(fis, fos);  
  179.         fis.close();  
  180.         fos.flush();  
  181.         fos.close();  
  182.   
  183.         if (delete) {  
  184.             file.delete();  
  185.         }  
  186.     }  
  187.   
  188.     /** 
  189.      * 数据解压缩 
  190.      *  
  191.      * @param is 
  192.      * @param os 
  193.      * @throws Exception 
  194.      */  
  195.     public static void decompress(InputStream is, OutputStream os)  
  196.             throws Exception {  
  197.   
  198.         GZIPInputStream gis = new GZIPInputStream(is);  
  199.   
  200.         int count;  
  201.         byte data[] = new byte[BUFFER];  
  202.         while ((count = gis.read(data, 0, BUFFER)) != -1) {  
  203.             os.write(data, 0, count);  
  204.         }  
  205.   
  206.         gis.close();  
  207.     }  
  208.   
  209.     /** 
  210.      * 文件解压缩 
  211.      *  
  212.      * @param path 
  213.      * @throws Exception 
  214.      */  
  215.     public static void decompress(String path) throws Exception {  
  216.         decompress(path, true);  
  217.     }  
  218.   
  219.     /** 
  220.      * 文件解压缩 
  221.      *  
  222.      * @param path 
  223.      * @param delete 
  224.      *            是否删除原始文件 
  225.      * @throws Exception 
  226.      */  
  227.     public static void decompress(String path, boolean delete) throws Exception {  
  228.         File file = new File(path);  
  229.         decompress(file, delete);  
  230.     }  
  231.   
  232. }  


罗嗦了半天,到底行不行? 
来个测试用例,测试用例如下所示: 
Java代码 
  1. /** 
  2.  * 2010-4-13 
  3.  */  
  4. package org.zlex.commons.compress.compress;  
  5.   
  6. import static org.junit.Assert.assertEquals;  
  7.   
  8. import java.io.DataInputStream;  
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.FileOutputStream;  
  12.   
  13. import org.junit.Test;  
  14.   
  15. /** 
  16.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
  17.  * @since 1.0 
  18.  */  
  19. public class GZipUtilsTest {  
  20.   
  21.     private String inputStr = "zlex@zlex.org,snowolf@zlex.org,zlex.snowolf@zlex.org";  
  22.   
  23.     @Test  
  24.     public final void testDataCompress() throws Exception {  
  25.   
  26.         System.err.println("原文:\t" + inputStr);  
  27.   
  28.         byte[] input = inputStr.getBytes();  
  29.         System.err.println("长度:\t" + input.length);  
  30.   
  31.         byte[] data = GZipUtils.compress(input);  
  32.         System.err.println("压缩后:\t");  
  33.         System.err.println("长度:\t" + data.length);  
  34.   
  35.         byte[] output = GZipUtils.decompress(data);  
  36.         String outputStr = new String(output);  
  37.         System.err.println("解压缩后:\t" + outputStr);  
  38.         System.err.println("长度:\t" + output.length);  
  39.   
  40.         assertEquals(inputStr, outputStr);  
  41.   
  42.     }  
  43.   
  44.     @Test  
  45.     public final void testFileCompress() throws Exception {  
  46.   
  47.         FileOutputStream fos = new FileOutputStream("d:/f.txt");  
  48.   
  49.         fos.write(inputStr.getBytes());  
  50.         fos.flush();  
  51.         fos.close();  
  52.   
  53.         GZipUtils.compress("d:/f.txt"false);  
  54.   
  55.         GZipUtils.decompress("d:/f.txt.gz"false);  
  56.   
  57.         File file = new File("d:/f.txt");  
  58.   
  59.         FileInputStream fis = new FileInputStream(file);  
  60.   
  61.         DataInputStream dis = new DataInputStream(fis);  
  62.   
  63.         byte[] data = new byte[(int) file.length()];  
  64.         dis.readFully(data);  
  65.   
  66.         fis.close();  
  67.   
  68.         String outputStr = new String(data);  
  69.         assertEquals(inputStr, outputStr);  
  70.     }  
  71. }  

结果如何? 
先看testDataCompress()方法控制台输出结果。 
控制台输出如下: 
引用

原文: zlex@zlex.org,snowolf@zlex.org,zlex.snowolf@zlex.org 
长度: 52 
压缩后:
长度: 45 
解压缩后: zlex@zlex.org,snowolf@zlex.org,zlex.snowolf@zlex.org 
长度: 52 

这里使用英文字符做测试,当输入字符串的字节数大于50左右时,压缩效果明显;如果这里使用中文压缩,可能当压缩上千字节时方能体现出压缩效果! 
对于文件操作,朋友们可以自行实验,我代码里的实现是按照gzip命令来的! 
举例来说: 
压缩时,将文件a.txt压缩为a.txt.gz,同时删除文件a.txt。 
解压缩时,将文件a.txt.gz解压缩为a.txt,同时删除文件a.txt.gz。 
注意执行testFileCompress方法,查看产生的文件!  你大可以放到linux上去做验证!

commons也提供了GZIP算法的实现,甚至更多种压缩算法(tar、bzip2等)的实现,有机会我将继续整理!


  • gzip.rar (1.5 KB)
  • 下载次数: 516

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/327851.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据结构树的基本操作_树的各类基本操作(数据结构)

#include "iostream"/*输入&#xff1a;ABC DE G FABC DE G F*/#include "bits/stdc.h"using namespace std;typedef struct bitnode{char data;bitnode *lchild,*rchild;} *bintree;bintree creatree(bintree &root)//先序创建树{char agetchar();if(…

下载bilibli网站视频

https://www.videofk.com/bilibili-video-download/ bilibili https://www.videofk.com/bilibili-video-download/search?urlhttps%3A%2F%2Fwww.bilibili.com%2Fvideo%2Fav50186988&selectbilibili

处理js乱码

1.将time.js编码格式更改外 2.在Tomcat设置VM-OPTION 选项为-Dfile.encodingutf-8

asp.net core 实战之 redis 负载均衡和quot;高可用quot;实现

1.概述 分布式系统缓存已经变得不可或缺,本文主要阐述如何实现redis主从复制集群的负载均衡,以及 redis的"高可用"实现, 呵呵双引号的"高可用"并不是传统意义的高可用哈,而是 redis集群挂了,并不影响asp.net core 的运行, 欲知详情,请看下文. 注意: 本文主…

Java IO: 其他字符流(下)

转载自 Java IO: 其他字符流(下)作者: Jakob Jenkov 译者: 李璟(jlee381344197gmail.com) 本小节会简要概括Java IO中的PushbackReader&#xff0c;LineNumberReader&#xff0c;StreamTokenizer&#xff0c;PrintWriter&#xff0c;StringReader&#xff0c;StringWriter。P…

java 长字符串 比较_Java字符串比较(3种方法)

字符串比较是常见的操作&#xff0c;包括比较相等、比较大小、比较前缀和后缀串等。在 Java 中&#xff0c;比较字符串的常用方法有 3 个&#xff1a;equals() 方法、equalsIgnoreCase() 方法、 compareTo() 方法。下面详细介绍这 3 个方法的使用。equals() 方法equals() 方法将…

IntelliJ IDEA 项目结构旁边出现 0%methods,0% lines covered 解决

IntelliJ IDEA 项目结构旁边出现 0%methods,0% lines covered 解决 windows 1.选中根目录文件夹 ctrl alt f6弹出如下框,取消勾选-->点击Show Selected就可以去掉了 mac 1.选中根目录文件夹 option fn command f6弹出如下框,取消勾选-->点击Show Select…

javaweb---简易邮件发送

邮件发送 2.jar包的支持 activation-1.1.1.jar mail-1.4.7.jar 3.授权码的获取 4.简易文本邮件发送的实现 由上图我们可以确定几个必须步骤 1.创建session对象 2.创建Transport对象 3.使用邮箱的用户名和授权码连上邮件服务器 4.创建一个Message对象&#xff08;需要传递…

Hibernate中使用Criteria查询及注解——(DeptTest.java)

DeptTest.java 测试类&#xff1a; 先创建Session&#xff1a; private Session session;private Transaction tx;Beforepublic void beforeMethod(){sessionnew Configuration().configure().buildSessionFactory().openSession();}关闭Session&#xff1a; Afterpublic void…

asp.net core 负载均衡集群搭建(centos7+nginx+supervisor+kestrel)

概述 本文目的是搭建三台asp.net core 集群, 并配上 nginx做负载均衡 首先准备要运行的源码 http://pan.baidu.com/s/1c20x0bA 准备三台服务器(或则虚拟机) 192.168.182.129 , 192.168.182.130 , 192.168.182.131 并将源码发布至三台服务器的 /root/aspnetcore/anuoapc 目录 …

Java IO教程

转载自 Java IO教程译文链接 作者&#xff1a;Jakob Jenkov 译者&#xff1a;Connor (cronnorcgmail.com) &#xff0c;李璟 校对&#xff1a;方腾飞 Java IO 是一套Java用来读写数据&#xff08;输入和输出&#xff09;的API。大部分程序都要处理一些输入&#xff0c;并由输…

Java web登录拦截器_SpringMVC拦截器(实现登录验证拦截器)

本例实现登陆时的验证拦截&#xff0c;采用SpringMVC拦截器来实现核心代码首先是index.jsp,显示链接String path request.getContextPath();String basePath request.getScheme()"://"request.getServerName()":"request.getServerPort()path"/&quo…

Java Poi 向excel中插入图片

博客 package com.unicom.yangjiabin.utils;import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.po…

visual studio for mac的离线安装初体验

微软2016 Connect 大会发布了visuo studio for mac的pre版本&#xff0c;由于工作原因&#xff0c;现在工作环境是mac&#xff0c;虽然开发现在是在用python&#xff0c;但一直关注着.net的发展&#xff0c;于是自己很激动的体验了一把&#xff0c;在张善友老师的提醒下,把安装…

JAVAWEB(笔记)

简介 web开发&#xff1a; web&#xff0c;网页的意思&#xff0c;www.baidu.com静态web html,sss提供给所有人看的数据始终不会发生变化&#xff01; 动态web 淘宝&#xff0c;几乎是所有的网站&#xff1b;提供给所有人看的数据始终会发生变化&#xff0c;每个人在不同的时…

Java IO: 其他字节流(上)

转载自 Java IO: 其他字节流(上)作者: Jakob Jenkov 译者: 李璟(jlee381344197gmail.com) 本小节会简要概括Java IO中的PushbackInputStream&#xff0c;SequenceInputStream和PrintStream。其中&#xff0c;最常用的是PrintStream&#xff0c;System.out和System.err都是Pri…

java中public private_java中public、private、protected区别

类中的数据成员和成员函数据具有的访问权限包括&#xff1a;public、private、protect、friendly(包访问权限)1、public&#xff1a;public表明该数据成员、成员函数是对所有用户开放的&#xff0c;所有用户都可以直接进行调用2、private&#xff1a;private表示私有&#xff0…

Excel转为图片

Java 将Excel转为图片、html、XPS、XML、CSV E_iceblue关注0人评论66人阅读2020-01-10 16:16:24 通过文档格式转换&#xff0c;可满足不同办公场合对文档操作的需求。本文将介绍转换Excel文档为其他常见文档格式的方法。通过文中的方法&#xff0c;可支持将Excel转换为包括PDF、…

Hibernate中使用Criteria查询及注解——( EmpCondition)

EmpCondition&#xff1a; 动态查询的条件类&#xff1a; package cn.bdqn.hibernate_Criteria.entity;import java.util.Date;/*** Criteria动态查询的条件类* author Administrator**/ public class EmpCondition {private String job;//职位private Double sal;//工资privat…

.NET Core 构建配置文件从 project.json 到 .csproj

从 .NET Core SDK 1.0 Preview 3 build 004056 开始&#xff0c;.NET Core 弃用 project.json&#xff0c;回归 .csproj&#xff0c;主要原因是为了兼容 MSBuild &#xff0c;详见 Announcing .NET Core Tools MSBuild “alpha” 。 如果你安装了 .NET Command Line Tools (1.0…