将整个 html 文件读取到字符串?

2022-09-01 05:02:15

有没有比以下更好的方法将整个html文件读取到单个字符串变量:

    String content = "";
    try {
        BufferedReader in = new BufferedReader(new FileReader("mypage.html"));
        String str;
        while ((str = in.readLine()) != null) {
            content +=str;
        }
        in.close();
    } catch (IOException e) {
    }

答案 1

有来自Apache Commons的IOUtils.toString(..)实用程序。

如果你正在使用,还有Files.readLines(..)Files.toString(..)。Guava


答案 2

你应该使用StringBuilder

StringBuilder contentBuilder = new StringBuilder();
try {
    BufferedReader in = new BufferedReader(new FileReader("mypage.html"));
    String str;
    while ((str = in.readLine()) != null) {
        contentBuilder.append(str);
    }
    in.close();
} catch (IOException e) {
}
String content = contentBuilder.toString();