【问题标题】:Content of url is UTF-8, but when I system.out the string it is not UTF-8 anymoreurl 的内容是 UTF-8,但是当我 system.out 字符串时它不再是 UTF-8
【发布时间】:2016-11-16 21:16:51
【问题描述】:

url 的内容是 UTF-8,但是当我 system.out 字符串时,它不再是 UTF-8。如何转换字符串以使其支持 utf-8?我得到了一些这样的词:

Objectgeörienteerd

我尝试过字节数组、输入流等,但没有奏效。

我的代码:

HttpURLConnection connection = null;
String thatUrl = url[0];
URL urly = new URL(thatUrl);
InputStream is = urly.openStream();
final StringBuffer buffer = new StringBuffer();
int counter;
while ((counter = is.read()) != -1) {
    buffer.append((char) counter);
}

【问题讨论】:

  • 您可能想要使用 buffer.toString()。您也可以尝试 PrintStream out = new PrintStream(System.out, true, "UTF-8"); out.println(缓冲区);因为它允许设置编码。
  • @JohnMorrison 这些与问题无关。

标签: java string encoding utf-8 character-encoding


【解决方案1】:

您正在使用 is.read() 一次读取 1 个字节的内容。 UTF-8 中的某些字符超过 1 个字节。每次遇到这些字符时,都会通过将每个单独的字节转换为字符来破坏它们。

一个简单的解决方案是将内容读入byte[](例如使用ByteArrayOutputStream),当您获得所有字节后,将它们转换为Stringnew String(byteArray, "UTF-8");

ByteArrayOutputStream out = new ByteArrayOutputStream();
int counter;
byte[] buffer = new byte[1024]; // Let's read up to 1KB at a time, it's faster
while((counter = is.read(buffer)) != -1)
    out.write(buffer, 0, counter);

// String output = new String(out.toByteArray(), "UTF-8");
String output = out.toString("UTF-8"); // Save an extra byte[] allocation

【讨论】:

  • 我的代码还是你的?因为如果我的代码不起作用,那比:(要严重得多。
  • 不幸的是它对我不起作用:(。它仍然将其打印为奇怪的字符
  • 您是否完全复制了我的代码?如果您将输出作为“ö”,则它只是 UTF-8 中“ö”中的字节转换为 ISO-8859-1(或类似)编码中的字符串。这正是我的代码要解决的问题。
  • @Jason 那么问题是什么(我假设你解决了它)?
  • 我认为它与 url 或类似的东西有关。
猜你喜欢
  • 2019-07-31
  • 2018-09-07
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多