| 1 |
// Copyright 2003, FreeHEP. |
| 2 |
package org.freehep.util.io; |
| 3 |
|
| 4 |
import java.io.FilterOutputStream; |
| 5 |
import java.io.IOException; |
| 6 |
import java.io.OutputStream; |
| 7 |
import java.util.zip.DeflaterOutputStream; |
| 8 |
|
| 9 |
/** |
| 10 |
* Special stream that can be used to write a header in uncompressed format, and |
| 11 |
* the rest of the stream in compressed format. This stream is used by SWF, to |
| 12 |
* compress the tail of the stream. |
| 13 |
* |
| 14 |
* @author Mark Donszelmann |
| 15 |
* @version $Id: CompressableOutputStream.java 8584 2006-08-10 23:06:37Z duns $ |
| 16 |
*/ |
| 17 |
public class CompressableOutputStream extends FilterOutputStream implements |
| 18 |
FinishableOutputStream { |
| 19 |
private boolean compress; |
| 20 |
|
| 21 |
private DeflaterOutputStream dos; |
| 22 |
|
| 23 |
/** |
| 24 |
* Creates a Compressable Output Stream from given stream. Initially the |
| 25 |
* stream does not compress. |
| 26 |
* |
| 27 |
* @param out stream to write to |
| 28 |
*/ |
| 29 |
public CompressableOutputStream(OutputStream out) { |
| 30 |
super(out); |
| 31 |
compress = false; |
| 32 |
} |
| 33 |
|
| 34 |
public void write(int b) throws IOException { |
| 35 |
if (compress) { |
| 36 |
dos.write(b); |
| 37 |
} else { |
| 38 |
out.write(b); |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
public void write(byte[] b, int off, int len) throws IOException { |
| 43 |
for (int i = 0; i < len; i++) { |
| 44 |
write(b[off + i]); |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
public void finish() throws IOException { |
| 49 |
if (compress) { |
| 50 |
dos.finish(); |
| 51 |
} |
| 52 |
if (out instanceof FinishableOutputStream) { |
| 53 |
((FinishableOutputStream) out).finish(); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
public void close() throws IOException { |
| 58 |
if (compress) { |
| 59 |
finish(); |
| 60 |
dos.close(); |
| 61 |
} else { |
| 62 |
out.close(); |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Start compressing from the next byte onwards. Flushes what is currently |
| 68 |
* in the buffer to the underlying stream and start compression from here. |
| 69 |
* |
| 70 |
* @throws IOException if write fails |
| 71 |
*/ |
| 72 |
public void startCompressing() throws IOException { |
| 73 |
out.flush(); |
| 74 |
compress = true; |
| 75 |
dos = new DeflaterOutputStream(out); |
| 76 |
} |
| 77 |
} |