1 7 8 package java.util.zip; 9 10 import java.io.OutputStream ; 11 import java.io.IOException ; 12 13 20 public 21 class GZIPOutputStream extends DeflaterOutputStream { 22 25 protected CRC32 crc = new CRC32 (); 26 27 30 private final static int GZIP_MAGIC = 0x8b1f; 31 32 36 private final static int TRAILER_SIZE = 8; 37 38 45 public GZIPOutputStream(OutputStream out, int size) throws IOException { 46 super(out, new Deflater (Deflater.DEFAULT_COMPRESSION, true), size); 47 usesDefaultDeflater = true; 48 writeHeader(); 49 crc.reset(); 50 } 51 52 57 public GZIPOutputStream(OutputStream out) throws IOException { 58 this(out, 512); 59 } 60 61 69 public synchronized void write(byte[] buf, int off, int len) 70 throws IOException 71 { 72 super.write(buf, off, len); 73 crc.update(buf, off, len); 74 } 75 76 82 public void finish() throws IOException { 83 if (!def.finished()) { 84 def.finish(); 85 while (!def.finished()) { 86 int len = def.deflate(buf, 0, buf.length); 87 if (def.finished() && len <= buf.length - TRAILER_SIZE) { 88 writeTrailer(buf, len); 90 len = len + TRAILER_SIZE; 91 out.write(buf, 0, len); 92 return; 93 } 94 if (len > 0) 95 out.write(buf, 0, len); 96 } 97 byte[] trailer = new byte[TRAILER_SIZE]; 100 writeTrailer(trailer, 0); 101 out.write(trailer); 102 } 103 } 104 105 108 109 private final static byte[] header = { 110 (byte) GZIP_MAGIC, (byte)(GZIP_MAGIC >> 8), Deflater.DEFLATED, 0, 0, 0, 0, 0, 0, 0 }; 121 122 private void writeHeader() throws IOException { 123 out.write(header); 124 } 125 126 130 private void writeTrailer(byte[] buf, int offset) throws IOException { 131 writeInt((int)crc.getValue(), buf, offset); writeInt(def.getTotalIn(), buf, offset + 4); } 134 135 139 private void writeInt(int i, byte[] buf, int offset) throws IOException { 140 writeShort(i & 0xffff, buf, offset); 141 writeShort((i >> 16) & 0xffff, buf, offset + 2); 142 } 143 144 148 private void writeShort(int s, byte[] buf, int offset) throws IOException { 149 buf[offset] = (byte)(s & 0xff); 150 buf[offset + 1] = (byte)((s >> 8) & 0xff); 151 } 152 } 153 | Popular Tags |