共計 932 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 編碼格式轉換的方法可以使用以下幾種方式:
1、使用 String
類的構造函數進行編碼轉換。例如,可以使用 String(byte[] bytes, Charset charset)
構造函數將字節數組轉換為指定編碼格式的字符串,或者使用 String(byte[] bytes, int offset, int length, Charset charset)
構造函數將字節數組的指定部分轉換為字符串。
byte[] bytes = "Hello World".getBytes(StandardCharsets.UTF_8);
String str = new String(bytes, StandardCharsets.UTF_16);
System.out.println(str); // 輸出: Hello World
2、使用 StandardCharsets
類提供的常量進行編碼轉換。Java 7 及以上版本提供了 StandardCharsets
類,其中包含一些常用的字符集編碼格式。
byte[] bytes = "Hello World".getBytes(StandardCharsets.UTF_8);
String str = new String(bytes, StandardCharsets.UTF_16);
System.out.println(str); // 輸出: Hello World
3、使用 Charset
類進行編碼轉換。Charset
類提供了 decode(ByteBuffer buffer)
方法將 ByteBuffer
對象轉換為字符串,或者使用 encode(CharBuffer buffer)
方法將字符串轉換為 ByteBuffer
對象。
ByteBuffer buffer = StandardCharsets.UTF_8.encode("Hello World");
String str = StandardCharsets.UTF_16.decode(buffer).toString();
System.out.println(str); // 輸出: Hello World
需要注意的是,編碼轉換可能會引發 UnsupportedEncodingException
異常,因此在使用時需要進行異常處理。
丸趣 TV 網 – 提供最優質的資源集合!
正文完