我从网上窃取了这个片段。但它看起来被限制在 4096 字节,并且是相当丑陋的 IMO。有人知道更好的方法吗?顺便说一句,我实际上正在使用 Groovy ...
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();
}
编辑:
我在 Groovy 中找到了更好的解决方案:
InputStream exportTemplateStream = getClass().getClassLoader().getResourceAsStream("export.template")
assert exportTemplateStream: "[export.template stream] resource not found"
String exportTemplate = exportTemplateStream.text
最佳答案
一些好的和快速的答案。但是我认为最好的是 Groovy 向 InputStream 添加了一个“getText”方法。所以我所要做的就是stream.text
。并请调用 4096 评论。
关于java - 将 Stream 转换为字符串 Java/Groovy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5837201/