将Java InputStream的内容写入OutputStream的简便方法

编程入门 行业动态 更新时间:2024-10-27 14:34:26
本文介绍了将Java InputStream的内容写入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所提到的, 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的简便方法

本文发布于:2023-06-11 15:13:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/637428.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简便   方法   内容   Java   InputStream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!