如何更快地读取缓冲阅读器

2022-09-01 05:31:52

我想优化此代码:

InputStream is = rp.getEntity().getContent();      

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

String text = "";
String aux = "";

while ((aux = reader.readLine()) != null) {
        text += aux;
      }

问题是我不知道如何读取缓冲阅读器的内容并将其复制到字符串中,比我上面的更快。我需要花尽可能少的时间。谢谢


答案 1

在循环中使用字符串串联是典型的性能杀手(因为字符串是不可变的,因此为每个串联复制整个越来越大的字符串)。请改为执行以下操作:

StringBuilder builder = new StringBuilder();
String aux = "";

while ((aux = reader.readLine()) != null) {
    builder.append(aux);
}

String text = builder.toString();

答案 2

你可以试试Apache IOUtils.toString。这就是他们所做的:

StringWriter sw = new StringWriter();
char[] buffer = new char[1024 * 4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
    sw.write(buffer, 0, n);
}
String text = sw.toString();

推荐