将 Java InputStream 的内容写入 OutputStream 的简单方法 [英] Easy way to write contents of a Java InputStream to an OutputStream

查看:38
本文介绍了将 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 的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆