Copy InputStream to File in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File InputStream FileInputStream Copy

In this Java tutorial we learn how to use the FileUtils utility class of Apache Commons IO library to copy bytes of an InputStream into a destination File.

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/

Copy InputStream to File using FileUtils.copyInputStreamToFile()

The first solution you can use is the FileUtils.copyInputStreamToFile() to copy an InputSteam to File as following example Java code.

CopyInputStreamToFile1.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class CopyInputStreamToFile1 {
    public static void main(String... args) {
        try {
            InputStream sourceInputStream = new FileInputStream("D:\\Data1\\test.docx");
            File destinationFile = new File("D:\\Data\\test.docx");

            FileUtils.copyInputStreamToFile(sourceInputStream, destinationFile);

            System.out.println("Copy InputSteam to file " + destinationFile + " success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Copy InputSteam to file D:\Data\test.docx success!

Copy InputStream to File using FileUtils.copyToFile()

The second solution is using the FileUtils.copyToFile() with a given InputSteam object and destination File as following example Java code.

CopyInputStreamToFile2.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class CopyInputStreamToFile2 {
    public static void main(String... args) {
        try {
            InputStream sourceInputStream = new FileInputStream("D:\\Data1\\test.docx");
            File destinationFile = new File("D:\\Data\\test.docx");

            FileUtils.copyToFile(sourceInputStream, destinationFile);

            System.out.println("Copy InputSteam to file " + destinationFile + " success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Copy InputSteam to file D:\Data\test.docx success!

Happy Coding 😊