001package com.hfg.util.io; 002 003// IMPORTS 004import com.hfg.exception.CompressionException; 005 006import java.io.ByteArrayInputStream; 007import java.io.ByteArrayOutputStream; 008import java.io.IOException; 009import java.util.zip.GZIPInputStream; 010import java.util.zip.GZIPOutputStream; 011 012//------------------------------------------------------------------------------ 013/** 014 Static methods to simplify GZIP compression/uncompression 015 016 @author Alex Taylor 017 */ 018//------------------------------------------------------------------------------ 019 020public class GZIP 021{ 022 023 //########################################################################## 024 // PUBLIC METHODS 025 //########################################################################## 026 027 028 //-------------------------------------------------------------------------- 029 public static byte[] compress(byte[] inValue) 030 throws CompressionException 031 { 032 return compress(inValue, 0, inValue.length); 033 } 034 035 //-------------------------------------------------------------------------- 036 public static byte[] compress(byte[] inValue, int inOffset, int inLength) 037 throws CompressionException 038 { 039 byte[] output; 040 041 try 042 { 043 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 044 GZIPOutputStream zipStream = new GZIPOutputStream(outStream); 045 046 zipStream.write(inValue, inOffset, inLength); 047 zipStream.close(); 048 output = outStream.toByteArray(); 049 } 050 catch (IOException e) 051 { 052 throw new CompressionException(e); 053 } 054 055 return output; 056 } 057 058 //-------------------------------------------------------------------------- 059 public static byte[] compress(String inValue) 060 throws CompressionException 061 { 062 byte[] output = null; 063 064 if (inValue != null) 065 { 066 output = compress(inValue.getBytes()); 067 } 068 069 return output; 070 } 071 072 //-------------------------------------------------------------------------- 073 public static byte[] uncompress(byte[] inValue) 074 throws CompressionException 075 { 076 byte[] output = null; 077 078 try 079 { 080 ByteArrayInputStream inStream = new ByteArrayInputStream(inValue); 081 GZIPInputStream zipStream = new GZIPInputStream(inStream); 082 083 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 084 085 byte[] buffer = new byte[2048]; 086 int bytesRead; 087 while ((bytesRead = zipStream.read(buffer, 0, buffer.length)) != -1) 088 { 089 outStream.write(buffer, 0, bytesRead); 090 } 091 092 output = outStream.toByteArray(); 093 inStream.close(); 094 outStream.close(); 095 } 096 catch (IOException e) 097 { 098 throw new CompressionException(e); 099 } 100 101 return output; 102 } 103 104 //-------------------------------------------------------------------------- 105 public static String uncompressToString(byte[] inValue) 106 throws CompressionException 107 { 108 return new String(uncompress(inValue)); 109 } 110 111 112}