这是我的问题:我有一个InputStream,已转换为字节数组,但我不知道运行时的字符集。我最初的想法是使用UTF-8处理所有内容,但是我发现使用ISO-8859-1编码并包含外国字符的流会出现奇怪的问题。(那些疯狂的瑞典人)
下面是相关代码:
为了模拟这个过程,我已经做了以下操作:
我错过了什么?
下面是相关代码:
IOUtils.toString(inputstream, "utf-8")
// Fails on iso8859-1 foreign characters
为了模拟这个过程,我已经做了以下操作:
new String("\u00F6")
// Returns ö as expected, since the default encoding is UTF-8
new String("\u00F6".getBytes("utf-8"), "utf-8")
// Also returns ö as expected.
new String("\u00F6".getBytes("iso-8859-1"), "utf-8")
// Returns \uffff, the unknown character
我错过了什么?
InputStream
中编码的(表面上的)字符的编码方式,那么您就无法将其转换为字符。就是这么简单。而且...为什么您会期望将编码转换为ISO-8859-1,然后从UTF-8解码任意字符呢? - Randall Schulznew String("\u00F6")
的值如预期一样,并不涉及编码。 - user166390Content-Type
标头及其相应的charset
参数存在的原因。 - Kristian Domagalanew String("\u00F6".getBytes("iso-8859-1"), "utf-8")
中的"utf-8"
参数 - 调用System.out.println(new String("\u00F6".getBytes("iso-8859-1")));
将非常好地打印出ö
. - Mr_and_Mrs_D