Java String getBytes()
方法使用指定的字元集將此String編碼為位元組序列,並將結果儲存到新的位元組陣列中。
語法
以下是此方法的語法 -
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
charsetName
- 字元集的名稱import java.io.*;
public class Test {
public static void main(String args[]) {
String Str1 = new String("Welcome to Tw511.com");
try {
String Str2 = new String( Str1.getBytes( "UTF-8" ));
System.out.println("Returned Value " + Str2 );
Str2 = new String (Str1.getBytes( "ISO-8859-1" ));
System.out.println("Returned Value " + Str2 );
} catch ( UnsupportedEncodingException e) {
System.out.println("Unsupported character set");
}
}
}
執行上面範例程式碼,得到以下結果:
Returned Value Welcome to Tw511.com
Returned Value Welcome to Tw511.com