How to read BufferedReader faster

天大地大妈咪最大 提交于 2019-12-17 15:48:16

问题


I want to optimize this code:

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

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

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

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

The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above. I need to spend as little time as possible. Thank you


回答1:


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



回答2:


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



回答3:


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



回答4:


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



回答5:


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



回答6:


You can use StringBuffer

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


来源:https://stackoverflow.com/questions/4666748/how-to-read-bufferedreader-faster

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