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


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

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

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

当前回答

我建议使用StringWriter类来解决这个问题。

StringWriter wt= new StringWriter();
IOUtils.copy(inputStream, wt, encoding);
String st= wt.toString();

其他回答

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

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();
    }
}

如果您使用的是AWS SDK v2,请调用IoUtils.toUtf8String():

public String convertStreamToString(InputStream is) {
    return IoUtils.toUtf8String(is);
}

Use:

InputStream in = /* Your InputStream */;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;

while ((read=br.readLine()) != null) {
    //System.out.println(read);
    sb.append(read);
}

br.close();
return sb.toString();

这是一个改编自org.apache.commons.io.IOUtils源代码的答案,适用于那些想要apache实现但不想要整个库的人。

private static final int BUFFER_SIZE = 4 * 1024;

public static String inputStreamToString(InputStream inputStream, String charsetName)
        throws IOException {
    StringBuilder builder = new StringBuilder();
    InputStreamReader reader = new InputStreamReader(inputStream, charsetName);
    char[] buffer = new char[BUFFER_SIZE];
    int length;
    while ((length = reader.read(buffer)) != -1) {
        builder.append(buffer, 0, length);
    }
    return builder.toString();
}

以下内容并没有回答最初的问题,而是回答了一些问题。

几个回答暗示了这种形式的循环

String line = null;
while((line = reader.readLine()) != null) {
  // ...
}

or

for(String line = reader.readLine(); line != null; line = reader.readLine()) {
    // ...
}

第一种形式通过在封闭作用域中声明一个变量“read”来污染封闭作用域的命名空间,该变量不会用于for循环之外的任何内容。第二个表单重复readline()调用。

这里有一种用Java编写这种循环的更简洁的方法。事实证明,for循环中的第一个子句不需要实际的初始值设定项值。这将变量“line”的范围保持在for循环的主体内。更优雅!我在任何地方都没有看到有人使用这个表单(几年前的一天我随机发现了它),但我一直在使用它。

for (String line; (line = reader.readLine()) != null; ) {
    //...
}