How to read BufferedReader faster

我们两清 提交于 2019-11-27 20:02:25

Using string concatenation in a loop is the classic performance killer (because Strings are immutable, the entire, increasingly large String is copied for each concatenation). Do this instead:

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

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

String text = builder.toString();

You can try Apache IOUtils.toString. This is what they do:

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

When BufferedReader reads from Socket, it is necessary to add 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();

One line solution:

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

I wrote a simple function to do this using StringBuilder and While loop with catching IOException inside.

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

You can use StringBuffer

while ((aux = reader.readLine()) != null) {
     stringBuffer.append(aux);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!