1 7 8 package java.util.zip; 9 10 import java.io.FilterOutputStream ; 11 import java.io.OutputStream ; 12 import java.io.InputStream ; 13 import java.io.IOException ; 14 15 24 public 25 class DeflaterOutputStream extends FilterOutputStream { 26 29 protected Deflater def; 30 31 34 protected byte[] buf; 35 36 39 40 private boolean closed = false; 41 42 50 public DeflaterOutputStream(OutputStream out, Deflater def, int size) { 51 super(out); 52 if (out == null || def == null) { 53 throw new NullPointerException (); 54 } else if (size <= 0) { 55 throw new IllegalArgumentException ("buffer size <= 0"); 56 } 57 this.def = def; 58 buf = new byte[size]; 59 } 60 61 67 public DeflaterOutputStream(OutputStream out, Deflater def) { 68 this(out, def, 512); 69 } 70 71 boolean usesDefaultDeflater = false; 72 73 77 public DeflaterOutputStream(OutputStream out) { 78 this(out, new Deflater ()); 79 usesDefaultDeflater = true; 80 } 81 82 88 public void write(int b) throws IOException { 89 byte[] buf = new byte[1]; 90 buf[0] = (byte)(b & 0xff); 91 write(buf, 0, 1); 92 } 93 94 102 public void write(byte[] b, int off, int len) throws IOException { 103 if (def.finished()) { 104 throw new IOException ("write beyond end of stream"); 105 } 106 if ((off | len | (off + len) | (b.length - (off + len))) < 0) { 107 throw new IndexOutOfBoundsException (); 108 } else if (len == 0) { 109 return; 110 } 111 if (!def.finished()) { 112 int stride = buf.length; 115 for (int i = 0; i < len; i+= stride) { 116 def.setInput(b, off + i, Math.min(stride, len - i)); 117 while (!def.needsInput()) { 118 deflate(); 119 } 120 } 121 } 122 } 123 124 130 public void finish() throws IOException { 131 if (!def.finished()) { 132 def.finish(); 133 while (!def.finished()) { 134 deflate(); 135 } 136 } 137 } 138 139 144 public void close() throws IOException { 145 if (!closed) { 146 finish(); 147 if (usesDefaultDeflater) 148 def.end(); 149 out.close(); 150 closed = true; 151 } 152 } 153 154 158 protected void deflate() throws IOException { 159 int len = def.deflate(buf, 0, buf.length); 160 if (len > 0) { 161 out.write(buf, 0, len); 162 } 163 } 164 } 165 | Popular Tags |