将InputStream读取为UTF-8?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (41)

我试图text/plain通过互联网逐行阅读文件。我现在的代码是:

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ó!,我正在使用它来测试编码。

如何读取InputStream为UTF-8?

提问于
用户回答回答于
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

需要:

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

或者从Java 7开始:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
用户回答回答于
    String file = "";

    try {

        InputStream is = new FileInputStream(filename);
        String UTF8 = "utf8";
        int BUFFER_SIZE = 8192;

        BufferedReader br = new BufferedReader(new InputStreamReader(is,
                UTF8), BUFFER_SIZE);
        String str;
        while ((str = br.readLine()) != null) {
            file += str;
        }
    } catch (Exception e) {

    }

扫码关注云+社区

领取腾讯云代金券