java字符集編碼格式轉(zhuǎn)換的方法是什么

小億
83
2023-11-22 19:36:50

在Java中,可以使用String類的構(gòu)造函數(shù)和getBytes()方法來(lái)進(jìn)行字符集編碼格式的轉(zhuǎn)換。

  1. 使用String類的構(gòu)造函數(shù):
    • String(byte[] bytes, Charset charset):將指定的字節(jié)數(shù)組按照指定的字符集編碼格式轉(zhuǎn)換為字符串。
    • String(byte[] bytes, int offset, int length, Charset charset):將指定的字節(jié)數(shù)組的指定部分按照指定的字符集編碼格式轉(zhuǎn)換為字符串。

示例代碼:

// 將字節(jié)數(shù)組按照UTF-8編碼格式轉(zhuǎn)換為字符串
byte[] bytes = {97, 98, 99}; // 字節(jié)數(shù)組表示"abc"
String str = new String(bytes, StandardCharsets.UTF_8);
System.out.println(str); // 輸出: abc
  1. 使用getBytes()方法:
    • byte[] getBytes(Charset charset):將字符串按照指定的字符集編碼格式轉(zhuǎn)換為字節(jié)數(shù)組。

示例代碼:

// 將字符串按照UTF-8編碼格式轉(zhuǎn)換為字節(jié)數(shù)組
String str = "abc";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
System.out.println(Arrays.toString(bytes)); // 輸出: [97, 98, 99]

在上述示例代碼中,StandardCharsets.UTF_8表示UTF-8編碼格式,你也可以根據(jù)需求選擇其他字符集編碼格式。

0