如何在Java中检查字符串的字符集?

在我的应用程序中,我从LDAP获取用户信息,有时完整的用户名出现在错误的字符集中。 例如:

ТеÑÑ61 ТеÑÑовиÑ61 

它也可以是英文或俄文并正确显示。 如果用户名更改,则会在数据库中更新。 即使我更改db中的值也不会解决问题。

我可以通过这样做来保存它

 new String(incorrect.getBytes("ISO-8859-1"), "UTF-8"); 

但是,如果我将它用于包含俄语字符的字符串(例如,“Тест61Тестович61”),我会得到类似这样的内容“???? 61 ???????? 61”。

你能否提出一些可以确定字符串字符串的东西?

java中的字符串AFAIK不保留其原始编码 – 它们始终以某种Unicodeforms存储在内部。 您想要检测原始流/字节的字符集 – 这就是为什么我认为您的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 

此外,您可以将任何编码的字符串转换为您想要的字符串,以utf-8为例:

 detector.getString(yourStr.getBytes(), "utf-8"); 

您的LDAP数据库设置不正确。 将数据放入其中的应用程序应该转换为已知的字符集编码,在您的情况下,可能是UTF_16。 选择一个标准。 所有检测编码的方法都是猜测。

编写该值的应用程序是唯一一个明确知道它正在使用哪种编码并且可以正确转换为其他编码(如UTF_16)的应用程序。

我有同样的问题。 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(); } 

完整描述: 检测Java字符串中的字符集 。

在您的Web应用程序中,您可以声明一个编码filter,以确保您以正确的编码方式接收数据。

  Explicitly set the encoding of the page to UTF-8 encodingFilter org.springframework.web.filter.CharacterEncodingFilter  encoding UTF-8   forceEncoding true   

弹簧提供的filter确保控制器/ servlet接收UTF-8参数。