Java:如何将InputStream传递给标准输出? [英] Java: How do I pipe InputStream to standard out?
问题描述
有一种简单(因此快速)的方法来实现这一目标吗?基本上只需要一些输入流,可能就像socket.getInputStream(),并让流的缓冲区自动重定向到标准输出?
Is there an easy (therefore quick) way to accomplish this? Basically just take some input stream, could be something like a socket.getInputStream(), and have the stream's buffer autmoatically redirect to standard out?
推荐答案
没有简单的方法可以做到这一点,因为 InputStream
有一个拉式接口,当 OutputStream
时有推式的。您需要某种抽取循环来从 InputStream
中提取数据并将它们推入 OutputStream
。像这样的东西(必要时在一个单独的线程中运行):
There are no easy ways to do it, because InputStream
has a pull-style interface, when OutputStream
has a push-style one. You need some kind of pumping loop to pull data from InputStream
and push them into OutputStream
. Something like this (run it in a separate thread if necessary):
int size = 0;
byte[] buffer = new byte[1024];
while ((size = in.read(buffer)) != -1) out.write(buffer, 0, size);
它已经在Apache Commons IO中实现为 IOUtils.copy()
It's already implemented in Apache Commons IO as IOUtils.copy()
这篇关于Java:如何将InputStream传递给标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!