共計 619 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 中將字節數組轉換成字符串的方法有兩種:
- 使用 String 的構造函數:可以使用 String 的構造函數將字節數組轉換成字符串,構造函數的形式為 new String(byte[] bytes)。例如:
byte[] bytes = {72, 101, 108, 108, 111};
String str = new String(bytes);
System.out.println(str); // 輸出:Hello
- 使用 String 的靜態方法:Java 提供了一個靜態方法 getBytes(),可以將字節數組轉換成字符串。例如:
byte[] bytes = {72, 101, 108, 108, 111};
String str = new String(bytes);
System.out.println(str); // 輸出:Hello
這兩種方法都可以將字節數組轉換成對應的字符串。需要注意的是,使用 String 的構造函數時,默認使用的是平臺的默認字符集。如果字節數組的字符集與平臺的默認字符集不一致,可能會導致亂碼問題。可以通過在構造函數中指定字符集解決這個問題,例如:
byte[] bytes = {72, 101, 108, 108, 111};
String str = new String(bytes, StandardCharsets.UTF_8);
System.out.println(str); // 輸出:Hello
在上述例子中,指定了 UTF- 8 字符集來解析字節數組。
丸趣 TV 網 – 提供最優質的資源集合!
正文完