範例

public static void main(String[] args) {
String str = "\u7b80\u4f53\u4e2d\u6587"; //$NON-NLS-1$
byte[] bytes = str.getBytes();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i]);
System.out.println(hex.substring(hex.length()-2));
}
}
解決方案
使用這個方法和字集參數來指定正確的字集。
java.lang.String.getBytes (javal.lang.String)

public static void main(String[] args) {
try {
String str = "\u7b80\u4f53\u4e2d\u6587"; //$NON-NLS-1$
byte[] bytes = str.getBytes("GB18030"); //$NON-NLS-1$
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i]);
System.out.println(hex.substring(hex.length()-2));
}
}catch (Exception e){
e.printStackTrace();
}
}
解決方案
使用 java.niojava.nio.charset 的類別
  • java.nio.charset.Charset
  • java.nio.charset.CharsetEncoder

public static void main(String[] args) {
try {
String str = "\u7b80\u4f53\u4e2d\u6587"; //$NON-NLS-1$
Charset cs = Charset.forName("GB18030"); //$NON-NLS-1$
CharsetEncoder encoder = cs.newEncoder();
ByteBuffer bb = encoder.encode(CharBuffer.wrap(str));
byte[] bytes = bb.array();
for (int i = 0, n = bb.limit()/* 在此請勿使用 bytes.length */; i < n ; i++) {
String hex = Integer.toHexString(bytes[i]);
System.out.println(hex.substring(hex.length()-2));
}
}catch (Exception e){
e.printStackTrace();
}
}