如何更快地阅读BufferedReader

时间:2011-01-12 08:44:27

标签: java optimization bufferedreader

我想优化此代码:

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

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

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

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

问题是我不知道如何阅读bufferedreader的内容并以比我上面更快的方式将其复制到String中。 我需要花费尽可能少的时间。 谢谢

6 个答案:

答案 0 :(得分:82)

在循环中使用字符串连接是 经典性能杀手(因为字符串是不可变的,所以为每个连接复制了整个越来越大的字符串)。这样做:

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

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

String text = builder.toString();

答案 1 :(得分:25)

您可以尝试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();

答案 2 :(得分:6)

BufferedReader从Socket读取时,需要添加bufferedReader.ready()

BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

StringBuilder sb= new StringBuilder();
String line = "";

while (br.ready() && (line = br.readLine()) != null) {
    sb.append(line + "\r\n");
}

String result = sb.toString();

答案 3 :(得分:1)

单行解决方案:

import java.io.*;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;

BufferedReader reader = ...;
String result = reader.lines().collect(joining(lineSeparator()));

答案 4 :(得分:0)

我编写了一个简单的函数,使用StringBuilder和While循环来捕获IOException。

public String getString(BufferedReader bufferedReader) {
    StringBuilder stringBuilder = new StringBuilder();
    String line = null;

    do {
        try {
            if ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (line != null);

    return stringBuilder.toString();
}

答案 5 :(得分:-1)

您可以使用StringBuffer

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