Copy InputStream to Writer in Java using Apache Commons IO

Tags: Copy IOUtils Apache Commons Apache Commons IO InputStream FileInputStream Writer FileWriter

In this Java tutorial we learn how to copy bytes from an InputStream object into Writer object using IOUtils utility 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 bytes from InputStream object to Writer object

The following Java program, we copy the file content from data.txt file into data-output.txt file using IOUtils.copy() method.

CopyInputStreamToWriter.java

import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;

public class CopyInputStreamToWriter {
    public static void main(String... args) {
        try {
            InputStream inputStream = new FileInputStream("D:\\Data\\data.txt");
            Writer writer = new FileWriter("D:\\Data\\data-output.txt");

            IOUtils.copy(inputStream, writer, "UTF-8");

            IOUtils.close(inputStream);
            IOUtils.close(writer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Happy Coding 😊