如何轻松地将BufferedReader转换为String? [英] 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;
}
上面的代码适用于我的servlet。它的目的是获取一个流,从中生成一个Json文件,然后将Json发送回客户端。
但是为了制作Json,我必须使用while循环读取 BufferedReader
object rd
。但是,我想将 rd
转换为尽可能少的代码行。我该怎么做?
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?
推荐答案
我建议使用commons IO库 - 那么它是一个简单的1个班轮:
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.
这篇关于如何轻松地将BufferedReader转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!