Java.lang.String.getBytes() 方法
描述
java.lang.String.getBytes(String charsetName) 方法使用命名的字符集将此字符串编码为字节序列,并将结果存储到新的字节数组中。
声明
以下是 java.lang.String.getBytes() 方法的声明。
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
参数
charset − 这是支持的字符集的名称。
返回值
此方法返回结果字节数组。
异常
UnsupportedEncodingException − 如果不支持命名字符集。
示例
下面的例子展示了 java.lang.String.getBytes() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) throws Exception {
// string with numbers and some special characters
String str = "!$0123@";
// byte array with charset
byte bval[] = str.getBytes("UTF8");
// prints the byte array
for (int i = 0; i < bval.length; i++) {
System.out.println(bval[i]);
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
33 36 48 49 50 51 64

