如果您有java.io.InputStream对象,应该如何处理该对象并生成String?


假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。

获取InputStream并将其转换为字符串的最简单方法是什么?

public String convertStreamToString(InputStream is) {
// ???
}

当前回答

如果使用流读取器,请确保在结束时关闭流

private String readStream(InputStream iStream) throws IOException {
    //build a Stream Reader, it can read char by char
    InputStreamReader iStreamReader = new InputStreamReader(iStream);
    //build a buffered Reader, so that i can read whole line at once
    BufferedReader bReader = new BufferedReader(iStreamReader);
    String line = null;
    StringBuilder builder = new StringBuilder();
    while((line = bReader.readLine()) != null) {  //Read till end
        builder.append(line);
        builder.append("\n"); // append new line to preserve lines
    }
    bReader.close();         //close all opened stuff
    iStreamReader.close();
    //iStream.close(); //EDIT: Let the creator of the stream close it!
                       // some readers may auto close the inner stream
    return builder.toString();
}

编辑:在JDK7+上,可以使用trywithresources构造。

/**
 * Reads the stream into a string
 * @param iStream the input stream
 * @return the string read from the stream
 * @throws IOException when an IO error occurs
 */
private String readStream(InputStream iStream) throws IOException {

    //Buffered reader allows us to read line by line
    try (BufferedReader bReader =
                 new BufferedReader(new InputStreamReader(iStream))){
        StringBuilder builder = new StringBuilder();
        String line;
        while((line = bReader.readLine()) != null) {  //Read till end
            builder.append(line);
            builder.append("\n"); // append new line to preserve lines
        }
        return builder.toString();
    }
}

其他回答

快速简便:

String result = (String)new ObjectInputStream( inputStream ).readObject();

你可以使用仙人掌:

String text = new TextOf(inputStream).asString();

UTF-8编码是默认编码。如果您需要另一个:

String text = new TextOf(inputStream, "UTF-16").asString();

最简单的方法,一行:

public static void main(String... args) throws IOException {
    System.out.println(new String(Files.readAllBytes(Paths.get("csv.txt"))));
}

如果需要将字符串转换为没有外部库的特定字符集,则:

public String convertStreamToString(InputStream is) throws IOException {
  try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
    is.transferTo(baos);
    return baos.toString(StandardCharsets.UTF_8);
  }
}

我做了一些计时测试,因为时间总是很重要的。

我试图以3种不同的方式将响应转换为字符串。(如下所示)为了可读性,我省略了try/catch块。

为了给出上下文,这是所有3种方法的前面代码:

   String response;
   String url = "www.blah.com/path?key=value";
   GetMethod method = new GetMethod(url);
   int status = client.executeMethod(method);

1)

 response = method.getResponseBodyAsString();

2)

InputStream resp = method.getResponseBodyAsStream();
InputStreamReader is=new InputStreamReader(resp);
BufferedReader br=new BufferedReader(is);
String read = null;
StringBuffer sb = new StringBuffer();
while((read = br.readLine()) != null) {
    sb.append(read);
}
response = sb.toString();

3)

InputStream iStream  = method.getResponseBodyAsStream();
StringWriter writer = new StringWriter();
IOUtils.copy(iStream, writer, "UTF-8");
response = writer.toString();

因此,在使用相同的请求/响应数据对每种方法运行了500次测试之后,以下是数字。再次,这些是我的发现,你的发现可能不完全相同,但我写这篇文章是为了向其他人说明这些方法的效率差异。

排名:方法#1进近#3-比#1慢2.6%2号进近——比1号进近慢4.3%

任何这些方法都是获取响应并从中创建字符串的适当解决方案。