簡體   English   中英

無法刷新Java中的DataOutputStream

[英]Can't flush DataOutputStream in Java

我想將一個雙精度數組放入DataInputStream中,並在控制台中使用DataOutputStream打印它。 我嘗試先將其轉換為字節數組。 我無法flush()DataOutputStream,因此它將在控制台中打印。 System.out.print(c)有效。

double[] b = { 7, 8, 9, 10 };

//double[] to byte[]
byte[] bytes = new byte[b.length * Double.SIZE];
ByteBuffer buf = ByteBuffer.wrap(bytes);
for (double d : b)
    buf.putDouble(d);
InputStream is = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(System.out);

int c;
try{
    while( (c = dis.read()) != -1){
        //System.out.print(c);
        dos.writeInt(c);
    }
    dos.flush();
}
catch(Exception e){
    System.out.println("error: " + e);
}

我想實現的輸出與System.out.print(c): 642800000064320000006434000000643600000000000000000000000000000000[...]

將字節寫入控制台可能會導致控制字符(無法打印),並可能導致意外結果。 如果您絕對需要查看文本表示形式,可以考慮使用ASCII轉換器,例如Base64。

但在您的示例中,替換

dos.writeInt(c); dos.writeChars(Integer.toString(n));

您將獲得預期的結果。 writeInt寫入代表當前int的4個字節,這可能導致各種控制字符。 writeChars寫入字符序列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM