Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to easily convert a BufferedReader to a String?

Tags:

java

json

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

like image 667
Jeungwoo Yoo Avatar asked Feb 23 '13 12:02

Jeungwoo Yoo


People also ask

Why BufferedReader is faster than FileReader?

Whereas, BufferedReader creates a buffer, and reads large amount of data using the given FileReader and loads it into a input buffer in the memory. Each time you want to read the file data, you can read it from the buffer( you don't have to directly access the disk drive every time) and hence is faster than FileReader.

How fast is BufferedReader in Java?

In an earlier post, I asked how fast the getline function in C++ could run through the lines in a text file. The answer was about 2 GB/s, certainly over 1 GB/s.


1 Answers

From Java 8:

rd.lines().collect(Collectors.joining()); 
like image 186
Gogol Avatar answered Sep 24 '22 15:09

Gogol