Java.lang.String.getBytes() 方法
描述
java.lang.String.getBytes() 方法使用平台的默认字符集将此字符串编码为字节序列,并将结果存储到新的字节数组中。
声明
以下是 java.lang.String.getBytes() 方法的声明。
public byte[] getBytes()
参数
NA
返回值
该方法返回结果字节数组。
异常
NA
示例
下面的例子展示了 java.lang.String.getBytes() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials point";
// copy contents of str1 to a byte array.
byte[] val = str1.getBytes();
// create string str1 using the contents of the byte array
String str2 = new String(val);
// prints the byte array.
System.out.println("String '" + str2 + "' is equal to str1");
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
String 'tutorials point' is equal to str1

