Re: Is there a DataOutput buffer in Java?
Bryan wrote:
I'm using a DataOutputStream to write primitive values to a network
socket. Is there some sort of DataOutput buffer I can use to write to
so I can print what I'm sending over the socket to the screen?
I suggest two classes.
First a class the forks the stream into two:
class ForkOutputStream extends OutputStream {
private final OutputStream out0;
private final OutputStream out1;
public ForkOutputStream(OutputStream out0, OutputStream out1) {
this.out0 = out0;
this.out1 = out1;
}
public synchronized void write(int b) throws IOException {
// This way around because:
// Assume out1 is some kind of monitoring stream.
// If out0 throws, we want the data already monitored.
// out0 exceptions are more important.
try {
out1.write(b);
} finally {
out0.write(b);
}
}
...
}
Then a class for dumbing output:
class DumpOutputSteam extends OutputStream {
private final byte[] buff = { 0, 0, ' ' };
private final OutputStream out;
public ForkOutputStream(OutputStream out) {
this.out = out;
}
private static byte toHexDigit(int b) {
b &= 0xf;
return b<10 ? (byte)('0'+b) : (byte)('a'-10+b);
}
public synchronized void write(int b) throws IOException {
buff[0] = toHexDigit(b>>4);
buff[1] = toHexDigit(b);
out.write(buff, 0, 3);
out.flush();
}
...
}
Put it together:
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(new ForkOutputStream(
rawOut, new DumpOutputStream(System.err)
))
);
(Disclaimer: I have not attempted to compile or test this code.)
Tom Hawtin