How to easily convert a BufferedReader to a String?

I found myself doing this today. Did not want to bring in IOUtils, so I went with this:

String response = new String();
for (String line; (line = br.readLine()) != null; response += line);

From Java 8:

rd.lines().collect(Collectors.joining());

I suggest using commons IO library - then it is a simple 1 liner:

String message = org.apache.commons.io.IOUtils.toString(rd);

of course, be aware that using this mechanism, a denial of service attack could be made, by sending a never ending stream of data that will fill up your server memory.


Use a variable as String like this:

BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
String line = "";
while((line = rd.readLine()) != null){

} 

Tags:

Java

Json