简体   繁体   English

将 Stream 转换为字符串 Java/Groovy

[英]Convert Stream to String Java/Groovy

I stole this snippet off the web.我从 web 上偷了这个片段。 But it looks to be limited to 4096 bytes and is quite ugly IMO.但它看起来被限制在 4096 字节,并且是相当丑陋的 IMO。 Anyone know of a better approach?有人知道更好的方法吗? I'm actually using Groovy btw...我实际上正在使用 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();
    }

EDIT:编辑:

I found a better solution in Groovy:我在 Groovy 中找到了更好的解决方案:

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

Some good and fast answers.一些好的和快速的答案。 However I think the best one is Groovy has added a "getText" method to InputStream.但是我认为最好的一个是 Groovy 在 InputStream 中添加了一个“getText”方法。 So all I had to do was stream.text .所以我所要做的就是stream.text And good call on the 4096 comment.并很好地致电 4096 评论。

For Groovy对于 Groovy

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

// Specify the encoding, and get the String object
//content = stream.getText("UTF-16") 
content = stream.getText("UTF-8") 

The InputStream class reference InputStream class 参考

The getText() without encoding, it will use current system encoding, ex ("UTF-8"). getText()没有编码,它将使用当前系统编码,例如(“UTF-8”)。

Try IOUtils from Apache Commons:尝试来自IOUtils Commons 的 IOUtils:

String s = IOUtils.toString(inputStream, "UTF-8");

It's reading the input in chunks of 4096 bytes(4KB), but the size of the actual string is not limited as it keeps reading more and appending it to the SringBuffer.它以 4096 字节(4KB)的块读取输入,但实际字符串的大小不受限制,因为它会不断读取更多内容并将其附加到 SringBuffer。

You can do it fairly easily using the Scanner class:您可以使用Scanner class 轻松完成:

String streamToSring(InputStream input) {
    Scanner s = new Scanner(input);
    StringBuilder builder = new StringBuilder();
    while (s.hasNextLine()) {
        builder.append(s.nextLine() +"\n");
    }
    return builder.toString();
}

That snippet has a bug: if the input uses a multi-byte character encoding, there's a good chance that a single character will span two reads (and not be convertable).该片段有一个错误:如果输入使用多字节字符编码,则单个字符很可能会跨越两次读取(并且不可转换)。 And it also has the semi-bug that it relies on the platform's default encoding.而且它还有一个依赖于平台默认编码的半错误。

Instead, use Jakarta Commons IO .相反,请使用Jakarta Commons IO In particular, the version of IOUtils.toString() that takes an InputStream and applies an encoding to it.特别是IOUtils.toString()的版本,它接受InputStream并对其应用编码。

For future reviewers who have similar problems, please note that both IOUtils from Apache, and Groovy's InputStream.getText() method require the stream to complete, or be closed before returning.以后有类似问题的审稿人请注意,Apache 的 IOUtils 和 Groovy 的 InputStream.getText() 方法都需要 stream 完成,否则返回前关闭。 If you are working with a persistent stream you will nead to deal with the "ugly" example that Phil originally posted, or work with non-blocking IO.如果您正在使用持久性 stream,您将需要处理 Phil 最初发布的“丑陋”示例,或者使用非阻塞 IO。

You can try something similar to this你可以尝试类似的东西

new FileInputStream( new File("c:/tmp/file.txt") ).eachLine { println it }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM