我的问题的背景如下:
在客户机/服务器架构(包括web服务通信)中,我在服务器端从客户端获得一个CSV文件。API给了我一个org.apache.commons.fileupload.FileItem
这些文件的允许代码页是代码页850和代码页1252。
一切正常运转,唯一的问题是欧元符号(欧元)。在代码页1252的情况下,我的代码无法正确处理欧元符号。当我将它打印到Eclipse中的控制台时,我看到的不是它,而是带有unicode U+00A4: U+00A4的标志。
目前,我使用以下代码。它分散在一些课程中。我已经提取了与之相关的线条。
byte[] inputData = call.getImportDatei().get();
// the following method works correctly
// it returns Charset.forName("CP850") or Charset.forName("CP1252")
final Charset charset = retrieveCharset(inputData);
char[] stringContents;
final StringBuffer sb = new StringBuffer();
final String s = new String(inputData, charset.name());
// here I see the problem with the euro sign already
// the following code shouldn't be the problem
// here some special characters are converted, but this doesn't affect the problem, so I removed those lines
stringContents = s.toCharArray();
for(final char c : stringContents){
sb.append(c);
}
final Reader stringReader = new StringReader(sb.toString());
// org.supercsv.io.CsvListReader
CsvListReader reader = new CsvListReader(stringReader, CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);
// now this reader is used to read the CSV content...我试过不同的东西:
FileItem.getInputStream()
我使用FileItem.getInputStream()来获得byte[],但是结果是一样的。
FileItem.getString()
当我使用FileItem.getString()时,它与代码页1252完美地工作:欧元符号被正确读取。当我将它打印到Eclipse中的控制台时,我会看到它。但是,对于代码页850,许多特殊字符是错误的。
FileItem.getString(字符串编码)
所以我的想法是使用FileItem.getString(字符串编码)。但是,我试图告诉他使用代码页1252的所有String都没有出现异常,而是产生了错误的结果。
例如,getString(Charset.forName("CP1252").name())导致问号而不是欧元符号。
当我使用org.apache.commons.fileupload.FileItem时,如何指定编码?
还是这条路不对?
谢谢你提前帮忙!
发布于 2013-07-24 15:29:02
当我将它打印到Eclipse中的控制台时,我会看到它。但是对于代码页850,可能特殊字符是错误的。
您正被误导,因为您过于关注Eclipse控制台提供的结果。底层数据是正确的,但是Eclipse错误地提供了它。在Windows上,默认情况下配置为使用cp1252来表示System.out.println()打印的字符。这样,原来用不同字符集解码的字符显然不能正确显示。
最好将Eclipse控制台重新配置为使用UTF-8来表示这些字符。UTF-8涵盖了世界所知的每一个字符。您可以通过将Window > Preferences > General > Workspace >设置为UTF-8来实现。
然后,考虑到您显然使用的是来自FileItem的Apache共用FileUpload,您可以以一种简单得多的方式以正确编码的Reader获得FileItem内容,如下所示:
byte[] content = fileItem.get();
Charset charset = retrieveCharset(content); // No idea what you're doing there, but kudos that it's returning the right charset.
Reader reader = new InputStreamReader(new ByteArrayInputStream(content), charset);
// ...请注意,当您打算在以后将此CSV写入System.out.println()以外的基于字符的输出流(如FileWriter )时,请不要忘记将字符集显式指定为UTF-8!你可以在OutputStreamWriter上这样做。否则,仍将使用平台默认编码,即Windows中的cp1252。
另请参阅:
https://stackoverflow.com/questions/17836472
复制相似问题