Adi*_*ova 27 java string character-encoding
在我的应用程序中,我从LDAP获取用户信息,有时完整的用户名出现在错误的字符集中.例如:
ТеÑÑ61 ТеÑÑовиÑ61
Run Code Online (Sandbox Code Playgroud)
它也可以是英文或俄文并正确显示.如果用户名更改,则会在数据库中更新.即使我更改了db中的值,它也不会解决问题.
我可以通过这样做来保存它
new String(incorrect.getBytes("ISO-8859-1"), "UTF-8");
Run Code Online (Sandbox Code Playgroud)
但是,如果我将它用于包含俄语字符的字符串(例如,"Тест61Тестович61"),我会得到类似这样的东西"???? 61 ???????? 61".
你能否提出一些可以确定字符串字符串的东西?
rad*_*dai 14
java中的字符串AFAIK不保留其原始编码 - 它们始终以某种Unicode形式存储在内部.你想检测原始流/字节的字符集 - 这就是为什么我认为你的String.toBytes()调用为时已晚.
理想情况下,如果您可以获取正在读取的输入流,则可以通过以下方式运行:http://code.google.com/p/juniversalchardet/
那里还有很多其他的charset探测器
我推荐Apache.tika CharsetDetector,非常友好和强大。
CharsetDetector detector = new CharsetDetector();
detector.setText(yourStr.getBytes());
detector.detect(); // <- return the result, you can check by .getName() method
Run Code Online (Sandbox Code Playgroud)
此外,您可以将任何编码字符串转换为您想要的字符串,以 utf-8 为例:
detector.getString(yourStr.getBytes(), "utf-8");
Run Code Online (Sandbox Code Playgroud)
我有同样的问题。Tika 太大,juniversalchardet 未检测到 ISO-8859-1。所以,我自己做了,现在在生产中运行良好:
public String convert(String value, String fromEncoding, String toEncoding) {
return new String(value.getBytes(fromEncoding), toEncoding);
}
public String charset(String value, String charsets[]) {
String probe = StandardCharsets.UTF_8.name();
for(String c : charsets) {
Charset charset = Charset.forName(c);
if(charset != null) {
if(value.equals(convert(convert(value, charset.name(), probe), probe, charset.name()))) {
return c;
}
}
}
return StandardCharsets.UTF_8.name();
}
Run Code Online (Sandbox Code Playgroud)
这里的完整描述:检测 Java 字符串中的字符集。
归档时间: |
|
查看次数: |
77862 次 |
最近记录: |