[英]BufferedOutputStream not writing to standardIO
我正在嘗試使用Robert Sedgwick在他的Algorithms 4E教科書中提供的BinaryStdOut.java類。 該課程的代碼可在他的網站上免費獲得,但是為了便於參考,我將在此處顯示其相關的摘要。
在上面提到的類中,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);
}
}
現在我的問題是測試代碼似乎沒有執行任何操作。 它可以編譯並成功運行,但是不會像在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");
}
}
寫入緩沖區后,需要刷新緩沖區:
// optimized if byte-aligned
if (N == 0) {
try {
out.write(x);
out.flush();
}
catch (IOException e) { e.printStackTrace(); }
return;
}
您的測試程序似乎什么都不顯示的原因是因為您正在打印DLE ,它是控制字符,不會在stdout中顯示。
這為我打印了一個世界,您是否選擇了一些沒有可顯示字形的字節? 而且您可能不應該這樣關閉System.out
(在BuffedOutputStream上調用close將其關閉並釋放與該流關聯的所有系統資源)。
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");
}
}
是的,您需要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
字符已打印。 ?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.