Beispiel
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
));
}
}
Lösung
Verwenden Sie die Methode mit dem Zeichensatzparameter, um den korrekten Zeichensatz anzugeben.
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();
}
}
Lösung
Verwenden Sie die Klassen in
java.nio
und
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();
}
}