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


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

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

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

当前回答

注意:这可能不是个好主意。此方法使用递归,因此将非常快地命中StackOverflowError:

public String read (InputStream is) {
    byte next = is.read();
    return next == -1 ? "" : next + read(is); // Recursive part: reads next byte recursively
}

其他回答

以下是我经过一些实验后提出的最优雅、纯Java(无库)解决方案:

public static String fromStream(InputStream in) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder out = new StringBuilder();
    String newLine = System.getProperty("line.separator");
    String line;
    while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append(newLine);
    }
    return out.toString();
}

你可以使用仙人掌:

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

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

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

一个很好的方法是使用Apache Commons IOUItils将InputStream复制到StringWriter中。。。类似于

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

甚至

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);

或者,如果不想混合流和写入器,可以使用ByteArrayOutputStream。

考虑到文件,首先应该获得java.io.Reader实例。然后可以将其读取并添加到StringBuilder中(如果我们不在多个线程中访问StringBuffer,我们就不需要StringBuffer了,StringBuilder速度更快)。这里的技巧是我们在块中工作,因此不需要其他缓冲流。块大小被参数化以用于运行时性能优化。

public static String slurp(final InputStream is, final int bufferSize) {
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    try (Reader in = new InputStreamReader(is, "UTF-8")) {
        for (;;) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
    }
    catch (UnsupportedEncodingException ex) {
        /* ... */
    }
    catch (IOException ex) {
        /* ... */
    }
    return out.toString();
}

此代码适用于新的Java学习者:

private String textDataFromFile;

public String getFromFile(InputStream myInputStream) throws FileNotFoundException, IOException {

    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(myInputStream));

    StringBuilder stringBuilder = new StringBuilder();

    String eachStringLine;

    while ((eachStringLine = bufferReader.readLine()) != null) {
        stringBuilder.append(eachStringLine).append("\n");
    }
    textDataFromFile = stringBuilder.toString();

    return textDataFromFile;
}