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

编程入门 行业动态 更新时间:2024-10-28 16:26:26
本文介绍了将 Java InputStream 的内容写入 OutputStream 的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我今天惊讶地发现,我无法找到任何简单的方法来将 InputStream 的内容写入 Java 中的 OutputStream.显然,字节缓冲区代码并不难编写,但我怀疑我只是遗漏了一些可以让我的生活更轻松(并且代码更清晰)的东西.

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).

那么,给定一个 InputStream in 和一个 OutputStream out,是否有一种更简单的方法来编写关注?

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); }

推荐答案

Java 9

从 Java 9 开始,InputStream 提供了一个名为 transferTo 的方法,其签名如下:

Java 9

Since Java 9, InputStream provides a method called transferTo with the following signature:

public long transferTo(OutputStream out) throws IOException

作为 documentation 声明,transferTo 将:

从此输入流中读取所有字节并将字节写入按照读取顺序给定输出流.回程时,这输入流将在流的末尾.这个方法不关闭无论是流.

Reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read. On return, this input stream will be at end of stream. This method does not close either stream.

此方法可能会无限期地阻止从输入流,或写入输出流.行为为输入和/或输出流异步关闭的情况,或传输过程中中断的线程,高输入和高输出特定于流,因此未指定

This method may block indefinitely reading from the input stream, or writing to the output stream. The behavior for the case where the input and/or output stream is asynchronously closed, or the thread interrupted during the transfer, is highly input and output stream specific, and therefore not specified

因此,为了将 Java InputStream 的内容写入 OutputStream,您可以编写:

So in order to write contents of a Java InputStream to an OutputStream, you can write:

input.transferTo(output);

更多推荐

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

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

发布评论

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

>www.elefans.com

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