@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; }
上面的代码用于我的servlet。其目的是获取流,从中创建一个Json文件,然后将Json发送回客户端。但是为了制作Json,我必须使用“ while”循环读取BufferedReader对象rd。但是,我想rd用尽可能少的代码行将其转换为字符串。我怎么做?
BufferedReader
rd
从Java 8:
rd.lines().collect(Collectors.joining());