サンプル

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 (java.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.nio および java.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()/* Here do not use bytes.length */; i < n ; i++) {
String hex = Integer.toHexString(bytes[i]);
System.out.println(hex.substring(hex.length()-2));
}
}catch (Exception e){
e.printStackTrace();
}
}