Java getBytes() 方法
getBytes() 方法有两种形式:
getBytes(String charsetName):使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
getBytes():使用平台的默认字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
语法
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
或
public byte[] getBytes()
参数
charsetName-- 支持的字符集名称。
返回值
返回 byte 数组。
实例
package com.jiaoben;
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