将输入流读取为 UTF-8

2022-08-31 10:13:32

我正在尝试通过互联网逐行读取文件。我现在拥有的代码是: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ó!

当我查看()时,我认为它是.我不认为这是一个问题,因为我可以没有问题。OutputStreamout> ¬°H√©ll√≥!OutputStreamout.println("é");

阅读UTF-8的任何想法?谢谢!InputStream


答案 1

解决了我自己的问题。此行:

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));

答案 2
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) {

}

试试这个,..:-)


推荐