ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeBoolean(true);
dos.writeDouble(2.345);
String s = baos.toString(); // 輸出亂碼 "@~oq?P"
toString() 默認用平台默認字符集(如 UTF-8)將原始字節解碼為字符串。但 DataOutputStream 寫入的是二進制格式(布爾 1 字節、double 8 字節 IEEE 754),非文本編碼,強行解碼當然亂碼。
byte[] bytes = baos.toByteArray();DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
boolean b = dis.readBoolean();
double d = dis.readDouble();
ByteArrayOutputStream 適合二進制協議組裝、內存中序列化,不適合直接轉字符串顯示。