简体   繁体   English

如何轻松地将BufferedReader转换为字符串?

[英]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. 上面的代码用于我的servlet。 Its purpose is to get a stream, make aa Json file from it, and then send the Json to the client back. 其目的是获取流,从中创建一个Json文件,然后将Json发送回客户端。 But in order to make Json, I have to read BufferedReader object rd using a "while" loop. 但是为了制作Json,我必须使用“ while”循环读取BufferedReader对象rd However I'd like to convert rd to string in as few lines of code as possible. 但是我想在尽可能少的代码行中将rd转换为字符串。 How do I do that? 我怎么做?

从Java 8:

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

I suggest using commons IO library - then it is a simple 1 liner: 我建议使用Commons IO库-那么这是一个简单的1班轮:

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. 当然,请注意,使用这种机制,可以通过发送永无休止的数据流来填满服务器内存,从而构成拒绝服务攻击。

I found myself doing this today. 我今天发现自己正在这样做。 Did not want to bring in IOUtils, so I went with this: 不想引入IOUtils,所以我这样做了:

String response = new String();
for (String line; (line = br.readLine()) != null; response += line);

Use a variable as String like this: 像这样使用变量作为String:

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

} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM