将 InputStream 读取为 UTF-8 [英] Reading InputStream as UTF-8

查看:132
本文介绍了将 InputStream 读取为 UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Internet 逐行读取 text/plain 文件.我现在拥有的代码是:

I'm trying to read from a text/plain file over the internet, line-by-line. The code I have right now is:

URL url = new URL("http://kuehldesign.net/test.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
LinkedList<String> lines = new LinkedList();
String readLine;

while ((readLine = in.readLine()) != null) {
    lines.add(readLine);
}

for (String line : lines) {
    out.println("> " + line);
}

文件 test.txt 包含 ¡Hélló!,我使用它来测试编码.

The file, test.txt, contains ¡Hélló!, which I am using in order to test the encoding.

当我查看 OutputStream (out) 时,我将其视为 >¬°H√©ll√≥!.我不认为这是 OutputStream 的问题,因为我可以毫无问题地执行 out.println("é");.

When I review the OutputStream (out), I see it as > ¬°H√©ll√≥!. I don't believe this is a problem with the OutputStream since I can do out.println("é"); without problems.

任何将 InputStream 读取为 UTF-8 的想法?谢谢!

Any ideas for reading form the InputStream as UTF-8? Thanks!

推荐答案

解决了我自己的问题.这一行:

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

必须是:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

或从 Java 7 开始:

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

这篇关于将 InputStream 读取为 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆