我試圖在他的算法4E教科書中使用由Robert Sedgwick提供的BinaryStdOut.java類。這個類的代碼可以在他的網站上免費獲得,但爲了便於參考,我將在這裏顯示相關的代碼片段。BufferedOutputStream不寫入standardIO
在上面提到的類,一個的BufferedOutputStream聲明如下
private static BufferedOutputStream out = new BufferedOutputStream(System.out);
這應該,如果我的理解是正確的,允許out.write()
基本上打印到標準輸出,就好像我是用System.out.print()
。
爲了測試這一點,我建立其主要功能是簡單地如下
public static void main(String[] args) {
BinaryStdOut.write(1);
}
這將整數1傳遞給BinaryStdOut的write()
方法,該方法是如下
public static void write(int x) {
writeByte((x >>> 24) & 0xff);
writeByte((x >>> 16) & 0xff);
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
的程序
writeByte()
代碼是:
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);
}
}
現在m問題是測試代碼似乎沒有做任何事情。它編譯並運行成功,但沒有任何打印在我的終端中,因爲如果我使用相同的整數執行System.out.print()
。
爲了查看BinaryStdOut類是否存在問題,我將BufferedOutputStream聲明的權限複製到主程序中,然後嘗試直接寫入該流,結果相同。
使用BufferedOutputStream.write()
時我有什麼遺漏嗎?
編輯:我的測試程序的主要功能目前看起來是這樣的:
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");
}
}
不要忘了'flush()' –
@SotiriosDelimanolis在哪裏可以放置'flush'我在我的主程序中放入'BufferedOutputStream.write()'之後立即添加了一個用於測試服務的應用程序,仍然沒有打印任何東西。 – sven
你可以把它放在'writeByte'(和其他寫入的方法)的末尾。 out.flush()'out'是你的'BufferedOutputStream'。 –