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

Java ByteArrayOutputStream 輸出地址而非內容:需 new String(byte[]) 轉換

     編輯:程式設計疑難解答

現象

ByteArrayOutputStream out = new ByteArrayOutputStream();
// ... 寫入數據 ...
byte[] r = out.toByteArray();
System.out.println(r); // 輸出 [B@6bbc4459 (數組地址)

原因

直接打印 `byte[]` 調用 `Object.toString()`,返回類名+哈希碼,而非數組內容。

正確轉換

System.out.println(new String(r, StandardCharsets.UTF_8)); // 指定編碼
// 或
System.out.println(out.toString(StandardCharsets.UTF_8.name())); // 直接用流方法

完整修正示例

public class Trans {
    public static void main(String[] args) throws Exception {
        String s = "abcdef";
        ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        new Trans().chang(in, out);
        System.out.println(out.toString(StandardCharsets.UTF_8.name())); // 輸出 ABCDEF
    }
    void chang(InputStream in, OutputStream out) throws IOException {
        int c;
        while ((c = in.read()) != -1) {
            out.write(Character.toUpperCase((char) c));
        }
    }
}

關鍵點

  • 字節數組 → 字符串**必須指定編碼**,否則平台默認編碼可能導致亂碼。
  • `ByteArrayOutputStream.toString(charsetName)` 內部已正確解碼,推薦使用。
  • 大小寫轉換用 `Character.toUpperCase` 處理字符而非字節,避免多字節字符損壞。

總結

不要直接打印字節數組,用 `new String(bytes, charset)` 或流的 `toString(charset)` 正確解碼為字符串。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved