1 2 3 4 package net.nutch.util; 5 6 import java.io.ByteArrayOutputStream ; 7 import java.io.ByteArrayInputStream ; 8 import java.io.IOException ; 9 import java.util.zip.GZIPInputStream ; 10 import java.util.zip.GZIPOutputStream ; 11 12 15 public class GZIPUtils { 16 17 private static final int EXPECTED_COMPRESSION_RATIO= 5; 18 private static final int BUF_SIZE= 4096; 19 20 26 public static final byte[] unzipBestEffort(byte[] in) { 27 return unzipBestEffort(in, Integer.MAX_VALUE); 28 } 29 30 37 public static final byte[] unzipBestEffort(byte[] in, int sizeLimit) { 38 try { 39 ByteArrayOutputStream outStream = 41 new ByteArrayOutputStream (EXPECTED_COMPRESSION_RATIO * in.length); 42 43 GZIPInputStream inStream = 44 new GZIPInputStream ( new ByteArrayInputStream (in) ); 45 46 byte[] buf = new byte[BUF_SIZE]; 47 int written = 0; 48 while (true) { 49 try { 50 int size = inStream.read(buf); 51 if (size <= 0) 52 break; 53 if ((written + size) > sizeLimit) { 54 outStream.write(buf, 0, sizeLimit - written); 55 break; 56 } 57 outStream.write(buf, 0, size); 58 written+= size; 59 } catch (Exception e) { 60 break; 61 } 62 } 63 try { 64 outStream.close(); 65 } catch (IOException e) { 66 } 67 68 return outStream.toByteArray(); 69 70 } catch (IOException e) { 71 return null; 72 } 73 } 74 75 76 80 public static final byte[] unzip(byte[] in) throws IOException { 81 ByteArrayOutputStream outStream = 83 new ByteArrayOutputStream (EXPECTED_COMPRESSION_RATIO * in.length); 84 85 GZIPInputStream inStream = 86 new GZIPInputStream ( new ByteArrayInputStream (in) ); 87 88 byte[] buf = new byte[BUF_SIZE]; 89 while (true) { 90 int size = inStream.read(buf); 91 if (size <= 0) 92 break; 93 outStream.write(buf, 0, size); 94 } 95 outStream.close(); 96 97 return outStream.toByteArray(); 98 } 99 100 103 public static final byte[] zip(byte[] in) { 104 try { 105 ByteArrayOutputStream byteOut= 107 new ByteArrayOutputStream (in.length / EXPECTED_COMPRESSION_RATIO); 108 109 GZIPOutputStream outStream= new GZIPOutputStream (byteOut); 110 111 try { 112 outStream.write(in); 113 } catch (Exception e) { 114 e.printStackTrace(); 115 } 116 117 try { 118 outStream.close(); 119 } catch (IOException e) { 120 e.printStackTrace(); 121 } 122 123 return byteOut.toByteArray(); 124 125 } catch (IOException e) { 126 e.printStackTrace(); 127 return null; 128 } 129 } 130 131 } 132 | Popular Tags |