代码如下
public class GZIPDemo { public static void main(String [] args) throws IOException{ String s ="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //我这里用字节流输出的,所以转正byte[] byte[] b = s.getBytes(); System.out.println("压缩前:"+b.length); //缓存数据用的字节数组流 ByteArrayOutputStream bout = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); //压缩用的是这个流 GZIPOutputStream gout = new GZIPOutputStream(bout); gout.write(b);//把b写入到缓冲区中,也就是ByteArrayOutputStream gout.close();//关闭流,也就是把数据全都刷到字节数组流中 b = bout.toByteArray();//这个字节数组流关闭之后还能用,不用担心,从他里面把压缩好的数据拿出来,还是放在byte[]中 System.out.println("压缩后:"+b.length); ByteArrayInputStream bis = new ByteArrayInputStream(b); GZIPInputStream gis =new GZIPInputStream(bis); int len = -1; byte [] b1 =new byte[1024]; StringBuilder sb = new StringBuilder(); while((len = gis.read(b1)) != -1){ bos.write(b1, 0, len); } bos.close(); System.out.println("解压之后:"+bos.toByteArray().length); System.out.println(bos.toString()); } private static void gizp2file() throws UnsupportedEncodingException, FileNotFoundException, IOException { // 做准备压缩一个字符文件,注,这里的字符文件要是GBK编码方式的12 BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream("d:/电脑提速.htm"), "GBK")); // 使用GZIPOutputStream包装OutputStream流,使其具体压缩特性,最后会生成test.txt.gz压缩包 // 并且里面有一个名为test.txt的文件 BufferedOutputStream out = new BufferedOutputStream( new GZIPOutputStream(new FileOutputStream("d:/电脑提速.htm.gz"))); System.out.println("开始写压缩文件..."); int c; while ((c = in.read()) != -1) { /* * 注,这里是压缩一个字符文件,前面是以字符流来读的,不能直接存入c,因为c已是Unicode * 码,这样会丢掉信息的(当然本身编码格式就不对),所以这里要以GBK来解后再存入。 */ out.write(String.valueOf((char) c).getBytes("GBK")); } in.close(); out.close(); System.out.println("开始读压缩文件..."); // 使用GZIPInputStream包装InputStream流,使其具有解压特性 BufferedReader in2 = new BufferedReader(new InputStreamReader( new GZIPInputStream(new FileInputStream("d:/PrintStreamTest.java.gz")), "GBK")); String s; // 读取压缩文件里的内容 while ((s = in2.readLine()) != null) { System.out.println(s); } in2.close(); } }
经测试 数据压缩无误;