将Stream转换为String Java/Groovy

phi*_*son 26 java groovy

我把这个片段从网上偷走了.但它看起来仅限于4096字节并且是非常难看的IMO.谁知道更好的方法?我实际上正在使用Groovy btw ...

String streamToString(InputStream input) {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = input.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }
Run Code Online (Sandbox Code Playgroud)

编辑:

我在Groovy中找到了一个更好的解决方案:

InputStream exportTemplateStream = getClass().getClassLoader().getResourceAsStream("export.template")
assert exportTemplateStream: "[export.template stream] resource not found"
String exportTemplate = exportTemplateStream.text
Run Code Online (Sandbox Code Playgroud)

phi*_*son 49

一些好的和快速的答案.但是我认为最好的是Groovy为InputStream添加了一个"getText"方法.所以我所要做的就是stream.text.并且很好地呼吁4096评论.

  • 所以你检查了文档_after_问?至少你可以粘贴一个使用它的例子. (2认同)

Aec*_*Liu 12

对于Groovy

filePath = ... //< a FilePath object
stream = filePath.read() //< InputStream object

content = stream.getText("UTF-16") //< Specify the encoding, and get the String object
Run Code Online (Sandbox Code Playgroud)

InputStream类引用

getText()不进行编码时,将使用当前的系统编码,前("UTF-8").


Tom*_*icz 8

尝试IOUtils使用Apache Commons:

String s = IOUtils.toString(inputStream, "UTF-8");
Run Code Online (Sandbox Code Playgroud)


Afi*_*efh 5

它以 4096 字节 (4KB) 的块读取输入,但实际字符串的大小不受限制,因为它会不断读取更多内容并将其附加到 SringBuffer。