2013-11-26 26 views
1

我試圖在他的算法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"); 
    } 
} 
+0

不要忘了'flush()' –

+0

@SotiriosDelimanolis在哪裏可以放置'flush'我在我的主程序中放入'BufferedOutputStream.write()'之後立即添加了一個用於測試服務的應用程序,仍然沒有打印任何東西。 – sven

+0

你可以把它放在'writeByte'(和其他寫入的方法)的末尾。 out.flush()'out'是你的'BufferedOutputStream'。 –

回答

1

你需要刷新你的緩衝區,你寫它後:

// optimized if byte-aligned 
if (N == 0) { 
    try { 
     out.write(x); 
     out.flush(); 
    } 
    catch (IOException e) { e.printStackTrace(); } 
    return; 
} 

爲什麼你的測試程序沒有按」的原因t似乎打印任何東西,因爲你正在打印一個DLE,這是一個控制字符,並不會顯示在標準輸出。

0

這爲我打印hello世界,你選擇了一些你沒有可顯示的字形的字節嗎?而且你可能不應該這樣關閉System.out(在BuffedOutputStream上調用關閉關閉它並釋放與該流關聯的所有系統資源)。

public static void main(String[] args) { 
    BufferedOutputStream out = new BufferedOutputStream(
     System.out); 
    String msg = "Hello, World!"; 
    try { 
    for (char c : msg.toCharArray()) { 
     out.write(c); 
    } 
    out.flush(); 
    } catch (IOException e) { 
    System.out.println("error"); 
    } 
} 
0

是的,你需要flush,爲什麼你需要flush是因爲Buffered輸出流的使用:

的BufferedOutputStream:

public BufferedOutputStream(OutputStream out) { 
    this(out, 8192);//default buffer size 
    } 
public synchronized void write(int b) throws IOException { 
    if (count >= buf.length) { 
     flushBuffer(); 
    } 
    buf[count++] = (byte)b; 
    } 

所以直到緩衝區充滿了8KB數據,內容將保持緩衝並且不會泄漏到控制檯。

write(16)上,您應該在控制檯(至少Eclipse IDE)上看到print char,如果您打印1601-1626,則應該看到打印的字符爲A-Z

相關問題