我很惊讶今天发现我无法找到将 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所提到的, org.apachemons.io.IOUtils 有一个名为 copy(InputStream,OutputStream) 这正是您正在寻找的。
所以,你有:
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.apachemons.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的简便方法
发布评论