📅  最后修改于: 2023-12-03 15:16:35.164000             🧑  作者: Mango
Java 字符串 getBytes() 方法将字符串编码成指定的字节数组,支持多种编码格式,如 UTF-8、ISO-8859-1 等。
此方法常用于进行网络传输、文件传输等需要字节流的操作中。
public byte[] getBytes()
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
返回一个字节数组,其中包含该字符串使用指定编码格式得到的字节。
String str = "Hello, world!";
byte[] bytes = str.getBytes();
System.out.println(Arrays.toString(bytes));
输出结果:
[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
以上示例中,使用默认编码格式(UTF-8)将字符串 "Hello, world!" 转换成字节数组,结果为 [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]。
在指定编码格式时,需要使用正确的编码名称。如果不确定编码格式,可以使用 Java 提供的 java.nio.charset.Charset 类来获取可用的编码格式集合。
SortedMap<String, Charset> charsets = Charset.availableCharsets();
System.out.println(charsets.keySet());
输出结果:
[Big5, Big5-HKSCS, EUC-JP, EUC-KR, GB18030, GB2312, GBK, IBM-Thai, IBM00858, IBM01140, IBM01141, IBM01142, IBM01143, IBM01144, IBM01145, IBM01146, IBM01147, IBM01148, IBM01149, IBM037, IBM1026, IBM1047, IBM273, IBM277, IBM278, IBM280, IBM284, IBM285, IBM297, IBM420, IBM424, IBM437, IBM500, IBM775, IBM850, IBM852, IBM855, IBM857, IBM860, IBM861, IBM862, IBM863, IBM864, IBM865, IBM866, IBM868, IBM869, IBM870, IBM871, IBM918, ISO-2022-CN, ISO-2022-JP, ISO-2022-JP-2, ISO-2022-KR, ISO-8859-1, ISO-8859-13, ISO-8859-15, ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, JIS_X0201, JIS_X0212-1990, KOI8-R, KOI8-U, Shift_JIS, TIS-620, US-ASCII, UTF-16, UTF-16BE, UTF-16LE, UTF-8, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, windows-31j, x-Big5-HKSCS-2001, x-Big5-Solaris, x-EUC-TW, x-IBM1006, x-IBM1025, x-IBM1046, x-IBM1097, x-IBM1098, x-IBM1112, x-IBM1122, x-IBM1123, x-IBM1124, x-IBM1364, x-IBM1381, x-IBM1383, x-IBM33722, x-IBM737, x-IBM856, x-IBM874, x-IBM875, x-IBM921, x-IBM922, x-IBM933, x-IBM942, x-IBM942C, x-IBM943, x-IBM943C, x-IBM948, x-IBM949, x-IBM949C, x-IBM950, x-IBM964, x-IBM970, x-ISCII91, x-ISO-2022-CN-CNS, x-ISO-2022-CN-GB, x-Johab, x-MS932_0213, x-MS950-HKSCS, x-MS949, x-MS950, x-MacArabic, x-MacCentralEurope, x-MacCroatian, x-MacCyrillic, x-MacDingbat, x-MacGreek, x-MacHebrew, x-MacIceland, x-MacRoman, x-MacRomania, x-MacSymbol, x-MacThai, x-MacTurkish, x-MacUkraine, x-PCK, x-SJIS_0213, x-UTF-16LE-BOM, x-euc-jp-linux, x-eucJP-Open, x-iso-8859-11, x-mswin-936, x-windows-50220, x-windows-50221, x-windows-874, x-windows-949]
综上,Java 字符串 getBytes() 方法是将字符串编码成指定的字节数组的方法,常用于进行网络传输、文件传输等需要字节流的操作中。要注意指定正确的编码格式名称,可以使用 Java 提供的 java.nio.charset.Charset 类获取可用的编码格式集合。