00001 package Encoder;
00002 import java.util.zip.*;
00003 import java.io.OutputStream;
00004 import java.io.IOException;
00005
00010 public class GZIPOutputStreamEx extends DeflaterOutputStream
00011 {
00015 protected CRC32 crc = new CRC32();
00016
00017
00018
00019
00020 private final static int GZIP_MAGIC = 0x8b1f;
00021
00029 public GZIPOutputStreamEx(OutputStream out, int size, int compression) throws IOException
00030 {
00031 super(out, new Deflater(compression, true), size);
00032 writeHeader();
00033 crc.reset();
00034 }
00035
00041 public GZIPOutputStreamEx(OutputStream out, int compression) throws IOException
00042 {
00043 this(out, 512, compression);
00044 }
00045
00054 public synchronized void write(byte[] buf, int off, int len)
00055 throws IOException
00056 {
00057 super.write(buf, off, len);
00058 crc.update(buf, off, len);
00059 }
00060
00067 public void finish() throws IOException
00068 {
00069 if (!def.finished())
00070 {
00071 def.finish();
00072 while (!def.finished())
00073 {
00074 deflate();
00075 }
00076 writeTrailer();
00077 }
00078 }
00079
00085 public void close() throws IOException
00086 {
00087 finish();
00088 out.close();
00089 }
00090
00091
00092
00093
00094 private void writeHeader() throws IOException
00095 {
00096 writeShort(GZIP_MAGIC);
00097 out.write(def.DEFLATED);
00098 out.write(0);
00099 writeInt(0);
00100 out.write(0);
00101 out.write(0);
00102 }
00103
00104
00105
00106
00107 private void writeTrailer() throws IOException
00108 {
00109 writeInt((int)crc.getValue());
00110 writeInt(def.getTotalIn());
00111 }
00112
00113
00114
00115
00116 private void writeInt(int i) throws IOException
00117 {
00118 writeShort(i & 0xffff);
00119 writeShort((i >> 16) & 0xffff);
00120 }
00121
00122
00123
00124
00125 private void writeShort(int s) throws IOException
00126 {
00127 out.write(s & 0xff);
00128 out.write((s >> 8) & 0xff);
00129 }
00130 }