Home >Java >javaTutorial >How Can I Easily Copy an InputStream to an OutputStream in Java?

How Can I Easily Copy an InputStream to an OutputStream in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 15:37:16189browse

How Can I Easily Copy an InputStream to an OutputStream in Java?

Writing InputStream Contents to OutputStream with Ease in Java

Copying the contents of an InputStream to an OutputStream in Java is a common task. While it's possible to write byte buffer code, there may be an easier solution.

Consider a scenario where you have an InputStream in and an OutputStream out. The following code exemplifies the conventional approach:

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}

Introducing Apache IOUtils

As WMR suggested, Apache's org.apache.commons.io.IOUtils class provides a method called copy(InputStream, OutputStream) that simplifies this task.

Using IOUtils, the code becomes more concise and straightforward:

IOUtils.copy(in, out);
in.close();
out.close();

While using IOUtils is recommended, if you have specific reasons for avoiding it, you can implement your own custom byte buffer code, as shown in the original code snippet.

The above is the detailed content of How Can I Easily Copy an InputStream to an OutputStream in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn