将Java InputStream的内容写入OutputStream的简便方法 [英] Easy way to write contents of a Java InputStream to an OutputStream
问题描述
我很惊讶今天发现我无法找到将 InputStream
的内容写入 OutputStream的任何简单方法。显然,字节缓冲区代码并不难写,但我怀疑我只是遗漏了一些会让我的生活更轻松(代码更清晰)的东西。
因此,在中给出 InputStream
和
OutputStream
out
,是否有更简单的方法来编写以下内容?
byte [] buffer = new byte [1024];
int len = in.read(buffer);
while(len!= -1){
out.write(buffer,0,len);
len = in.read(buffer);
}
正如WMR所提到的,<$来自Apache的c $ c> org.apache.commons.io.IOUtils 有一个名为 copy(InputStream,OutputStream)
这正是您正在寻找的。 p>
所以,你有:
InputStream in;
OutputStream out;
IOUtils.copy(in,out);
in.close();
out.close();
...在您的代码中。
你有没有理由避免 IOUtils
?
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream
to an OutputStream
in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).
So, given an InputStream
in
and an OutputStream
out
, is there a simpler way to write the following?
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
As WMR mentioned, org.apache.commons.io.IOUtils
from Apache has a method called copy(InputStream,OutputStream)
which does exactly what you're looking for.
So, you have:
InputStream in;
OutputStream out;
IOUtils.copy(in,out);
in.close();
out.close();
...in your code.
Is there a reason you're avoiding IOUtils
?
这篇关于将Java InputStream的内容写入OutputStream的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!