Copy File to OutputStream in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO Copy File FileOutputStream OutputStream

In this Java tutorial we learn how to copy contents of a given File object into OutputStream using FileUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to Copy File to OutputStream in Java

The following example shows you how to copy all bytes from a file into an OutputStream using the method FileUtils.copyFile() of Apache Commons IO library.

CopyFileToOutputStream.java

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class CopyFileToOutputStream {
    public static void main(String... args) {
        try {
            File sourceFile = new File("D:\\Data\\data.txt");
            OutputStream outputStream = new FileOutputStream("D:\\Data\\dataDestination.txt");
            FileUtils.copyFile(sourceFile, outputStream);

            IOUtils.close(outputStream);
            System.out.println("Copy " + sourceFile + " to OutputStream success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Copy D:\Data\data.txt to OutputStream success!

Happy Coding 😊