将InputStream读取为UTF-8 [英] Reading InputStream as UTF-8
问题描述
我正试图通过互联网逐行读取 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屋!