Jeungwoo Yoo
Jeungwoo Yoo

Reputation: 1119

How to easily convert a BufferedReader to a String?

@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?

Upvotes: 78

Views: 138070

Answers (5)

viking
viking

Reputation: 319

Since Java 10, you can do the following:

StringWriter writer = new StringWriter();
new InputStreamReader(request.getInputStream(), "UTF-8").transferTo(writer);
System.out.println(writer.toString());

Note that this approach has the advantage of properly handling escape characters, properly buffering the characters for greater efficiency, using a StringBuffer to construct the string at the end, and not bringing in external libraries.

Since Java 9, you can convert directly from an InputStream to a StringWriter like this:

 StringWriter writer = new StringWriter();
 request.getInputStream().transferTo(writer);
 System.out.println(writer.toString());

Upvotes: 2

Gogol
Gogol

Reputation: 1690

From Java 8:

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

Upvotes: 159

user2665773
user2665773

Reputation: 306

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

Upvotes: 29

Use a variable as String like this:

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

} 

Upvotes: 2

Richard
Richard

Reputation: 9928

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.

Upvotes: 62

Related Questions