Java.lang.String.getBytes() 方法
描述
java.lang.String.getBytes(Charset charset) 方法使用给定的字符集将此字符串编码为字节序列,并将结果存储到新的字节数组中。
声明
以下是 java.lang.String.getBytes() 方法的声明。
public byte[] getBytes(Charset charset)
参数
charset − 这是用于对字符串进行编码的字符集。
返回值
此方法返回结果字节数组。
异常
NA
示例
下面的例子展示了 java.lang.String.getBytes() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
try {
String str1 = "admin";
System.out.println("string1 = " + str1);
// copy the contents of the String to a byte array
byte[] arr = str1.getBytes("ASCII");
String str2 = new String(arr);
// print the contents of the byte array
System.out.println("new string = " + str2);
} catch(Exception e) {
System.out.print(e.toString());
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
string1 = admin new string = admin

