在Java中,如何使用Google的guava CharStreams.toString进程中的inputStream?
我正在执行一个进程,并希望将其输出读入字符串中。我希望使用 Guava CharStreams.toString(InputSupplier
。不幸的是,Process的getInputStream()
返回的流是InputStream
类型,而不是InputSupplier。我如何使用它来创建一个 InputSupplier
以与 toString()
一起使用?
理想情况下我可以做这样的事情:
CharStreams.toString(CharStreams.newReaderSupplier(process.getInputStream()))
但是你不能从InputStream构造一个InputSupplier,而且我很难找到如何做到这一点。
I am executing a process and want to read in its output into a String. Rather than deal with try/catch/finally, I am hoping to use the Guava CharStreams.toString(InputSupplier<R> supplier)
. Unfortunately, the stream returned by Process's getInputStream()
is type InputStream
and not InputSupplier. How can I use this to create an InputSupplier
for use with toString()
?
Ideally I could do something like this:
CharStreams.toString(CharStreams.newReaderSupplier(process.getInputStream()))
But you cannot construct an InputSupplier from an InputStream and I am having trouble finding out how to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我还没有找到用番石榴做到这一点的方法。我相信开发商这样做是有充分理由的。在保持最小化的同时,我得到的最接近的是:
我使用了 CharStreams 中的 newReaderSupplier,因此您不必使用 InputStreamReader 包装它。
I haven't found a way to do this with guava yet. I am sure the developer has a good reason for this. The closest I have gotten without while keep it minimal is:
I have used
newReaderSupplier
from CharStreams so you don't have to wrap it withInputStreamReader
.怎么样:
它正在使用
CharStreams.toString(Readable)
。What about this:
It is using
CharStreams.toString(Readable)
.到目前为止,这是我能做的最好的事情:
So far this is the best I could do:
正确的做法——以及 Guava 试图促使你做的事情——是改变为你提供 InputStream 的代码,改为为你提供一个 InputSupplier。
这样做的原因是,这样,Guava 获取流,读取字符串,然后关闭它,并且在 Guava 关闭它之后你不会意外地使用它,因为你一开始就没有对 InputStream 的引用。这消除了很多潜在的错误。
另一个重载 CharStreams.toString(Readable) 不会关闭 Readable。如果您想拥有自己的特殊逻辑来关闭输入流,Guava 可以让您这样做。
Guava 相当于 IOUtils.toString(InputStream) 说得比我好可以。
The Right Thing to Do -- and what Guava's trying to push you into doing -- is to change the code that gives you the InputStream to give you an InputSupplier instead.
The reason for this is that this way, Guava gets the stream, reads the string, and closes it, and you can't accidentally use it after Guava's closed it, because you never had a reference to the InputStream in the first place. This eliminates a lot of potential bugs.
The other overload, CharStreams.toString(Readable), does not close the Readable. If you want to have your own, special logic for closing the input stream, this is Guava's way of letting you do that.
Guava equivalent for IOUtils.toString(InputStream) says it better than I could.
这应该可以做到:
这是一个完整用法的现实例子:
我知道这并不是真正的问题,但为了比较,他就是你如何使用 IOUtils 做到这一点 - IMO 更干净一些:
This should do it:
And here is a real life example of the complete usage:
I know this insn't really in question, but for comparison sake he is how you'd do it with IOUtils - which IMO is a bit cleaner: