我需要使用这个来获取数百万字符串的字节:
String str="blablabla...."; // some UTF-16LE encoding string extracted from DB
bytes=str.getBytes("UTF-16LE")
但这非常缓慢。有getBytes
的自定义快速版本,但它们不支持UTF-16LE
。例如,这是其中之一:
// http://stackoverflow.com/questions/12239993/why-is-the-native-string-getbytes-method-slower-than-the-custom-implemented-getb
private static byte[] getBytesFast(String str) {
final char buffer[] = new char[str.length()];
final int length = str.length();
str.getChars(0, length, buffer, 0);
final byte b[] = new byte[length];
for (int j = 0; j < length; j++)
b[j] = (byte) buffer[j];
return b;
}
是否有使用UTF-16LE编码将Java字符串转换为字节数组的类似快速解决方案?
答案 0 :(得分:3)
此版本将生成UTF16LE字节数组:
private static byte[] getBytesUTF16LE(String str) {
final int length = str.length();
final char buffer[] = new char[length];
str.getChars(0, length, buffer, 0);
final byte b[] = new byte[length*2];
for (int j = 0; j < length; j++) {
b[j*2] = (byte) (buffer[j] & 0xFF);
b[j*2+1] = (byte) (buffer[j] >> 8);
}
return b;
}
测试:
String test = "UTF16 Ελληνικά Русский 日本語";
byte[] bytes = test.getBytes("UTF-16LE");
byte[] bytes2 = getBytesUTF16LE(test);
System.out.println(Arrays.equals(bytes, bytes2));