首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java DataOutputStream 寫入 ByteArrayOutputStream:需先 flush DataOutputStream 再取位元組陣列

     編輯:程式設計綜合問答

問題代碼

ByteArrayOutputStream dos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(dos));
out.writeDouble(point);
out.writeInt(num);
out.writeUTF(str);
out.writeUTF(str02);
dos.flush();                 // 錯誤順序
b2 = dos.toByteArray();

結果讀取時資料不完整或亂碼。

原因

DataOutputStream 內部有緩衝 (透過 BufferedOutputStream),資料尚在 out 緩衝區,**未寫入底層 dos**。呼叫 dos.flush() 無效,必須先 out.flush()。

正確順序

out.writeUTF(str02);
out.flush();       // 1. 先 flush DataOutputStream,資料才進入 dos
dos.flush();       // 2. 再 flush ByteArrayOutputStream (可選,通常無緩衝)
b2 = dos.toByteArray();

完整可執行範例

public static byte[] write() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (DataOutputStream out = new DataOutputStream(baos)) { // try-with-resources 自動 close/flush
        out.writeDouble(3.14159);
        out.writeInt(2628);
        out.writeUTF("我是汪洋");
        out.writeUTF("劉林是我同學");
    }
    return baos.toByteArray();
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved