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));
}
}
}
不要直接打印字節數組,用 `new String(bytes, charset)` 或流的 `toString(charset)` 正確解碼為字符串。