How to easily convert a BufferedReader to a String?

JavaJson

Java Problem Overview


@POST
@Path("/getphotos")
@Produces(MediaType.TEXT_HTML)
public String getPhotos() throws IOException{
    // DataInputStream rd = new DataInputStream(request.getInputStream());
    BufferedReader rd = new BufferedReader(
        new InputStreamReader(request.getInputStream(), "UTF-8")
    );
	String line = null;
	String message = new String();
	final StringBuffer buffer = new StringBuffer(2048);
	while ((line = rd.readLine()) != null) {
        // buffer.append(line);
		message += line;
    }
	System.out.println(message);
	JsonObject json = new JsonObject(message);
	return message;
}

The code above is for my servlet. Its purpose is to get a stream, make a a Json file from it, and then send the Json to the client back. But in order to make Json, I have to read BufferedReader object rd using a "while" loop. However I'd like to convert rd to string in as few lines of code as possible. How do I do that?

Java Solutions


Solution 1 - Java

From Java 8:

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

Solution 2 - Java

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.

Solution 3 - Java

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

Solution 4 - Java

Use a variable as String like this:

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

} 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeungwoo YooView Question on Stackoverflow
Solution 1 - JavaGogolView Answer on Stackoverflow
Solution 2 - JavaRichardView Answer on Stackoverflow
Solution 3 - Javauser2665773View Answer on Stackoverflow
Solution 4 - JavaArmando Esparza GarcíaView Answer on Stackoverflow