I am attempting to use the BinaryStdOut.java class provided by Robert Sedgwick in his Algorithms 4E textbook. The code for this class is freely available on his website, but for ease of reference, I will show relevant snippets of it here.
In the class mentioned above, a BufferedOutputStream is declared as follows
private static BufferedOutputStream out = new BufferedOutputStream(System.out);
This should, if my understanding is correct, allow for out.write()
to essentially print to the standard out just as if I were to use System.out.print()
.
In order to test this, I built a program whose main functions was simply as follows
public static void main(String[] args) {
BinaryStdOut.write(1);
}
This would pass the integer 1 to the BinaryStdOut's write()
method, which is as follows
public static void write(int x) {
writeByte((x >>> 24) & 0xff);
writeByte((x >>> 16) & 0xff);
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
The writeByte()
code is:
private static void writeByte(int x) {
assert x >= 0 && x < 256;
// optimized if byte-aligned
if (N == 0) {
try { out.write(x); }
catch (IOException e) { e.printStackTrace(); }
return;
}
// otherwise write one bit at a time
for (int i = 0; i < 8; i++) {
boolean bit = ((x >>> (8 - i - 1)) & 1) == 1;
writeBit(bit);
}
}
Now my problem is that the test code does not appear to do anything. It compiles and runs successfully, but nothing gets printed in my Terminal as it would if I did a System.out.print()
with the same integer.
In order to see if the problem was with the BinaryStdOut class, I copied the BufferedOutputStream declaration right into my main program and then attempted to write directly to that stream, with the same result.
Is there something that I am missing with using BufferedOutputStream.write()
?
EDIT: My test program's main function currently looks like this:
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedOutputStream out = new BufferedOutputStream(System.out);
try {out.write(16);
out.flush();
out.close();}
catch(IOException e){
System.out.println("error");
}
}
You need to flush your buffer after you write to it:
// optimized if byte-aligned
if (N == 0) {
try {
out.write(x);
out.flush();
}
catch (IOException e) { e.printStackTrace(); }
return;
}
The reason why your test program doesn't seem to print anything is because you are printing a DLE, which is a control character, and that won't show up in stdout.