如何更快读取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中。 我需要花尽可能less的时间。 谢谢

在循环中使用string连接是经典的性能杀手(因为string是不可变的,整个越来越大的string被复制每个级联)。 做这个,而不是:

 StringBuilder builder = new StringBuilder(); String aux = ""; while ((aux = reader.readLine()) != null) { builder.append(aux); } String text = builder.toString(); 

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

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

我写了一个简单的函数来使用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(); } 

你可以使用StringBuffer

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