我把这个片段从网上偷走了.但它看起来仅限于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评论.
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)
在getText()不进行编码时,将使用当前的系统编码,前("UTF-8").
尝试IOUtils使用Apache Commons:
String s = IOUtils.toString(inputStream, "UTF-8");
Run Code Online (Sandbox Code Playgroud)