01: package uk.org.ponder.streamutil;
02:
03: import java.io.InputStream;
04: import java.io.OutputStream;
05: import java.io.ByteArrayOutputStream;
06: import java.io.ByteArrayInputStream;
07:
08: import uk.org.ponder.util.Logger;
09:
10: /** This class abstracts the idea of an array of bytes, and handles the task of
11: * converting it (the array, not the idea) to and from input and output streams.
12: */
13:
14: public class BytePen {
15: private InputStream stashed;
16: private byte[] bytes;
17:
18: /** Returns an output stream to which the byte array contents can be written.
19: * @return An output stream to which the byte array contents can be written.
20: */
21: public OutputStream getOutputStream() {
22: final ByteArrayOutputStream togo = new ByteArrayOutputStream();
23: OutputStream toreallygo = new TrackerOutputStream(togo,
24: new StreamClosedCallback() {
25: public void streamClosed(Object o) {
26: Logger.println("BytePen OutputStream closed",
27: Logger.DEBUG_INFORMATIONAL);
28: bytes = togo.toByteArray();
29: }
30: });
31: return toreallygo;
32: }
33:
34: /** Sets the input stream from which the byte array can be read.
35: * @param is The input stream from which the byte array can be read.
36: */
37: public void setInputStream(InputStream is) {
38: stashed = is;
39: }
40:
41: /** Returns an input stream from which the byte array can be read. If the
42: * array was specified via <code>setInputStream</code>, the original input
43: * stream will be returned.
44: * @return An input stream from which the byte array can be read.
45: */
46:
47: public InputStream getInputStream() {
48: if (stashed != null) {
49: InputStream togo = stashed;
50: stashed = null;
51: return togo;
52: } else
53: return new ByteArrayInputStream(bytes);
54: }
55:
56: }
|