Convert Writer into BufferedWriter in Java using Apache Commons IO

Tags: Convert IOUtils Apache Commons Apache Commons IO Writer FileWriter BufferedWriter

In this Java tutorial we learn how to use the IOUtils utility class in Apache Commons IO to convert an Writer object into a BufferedWriter object in Java.

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 convert Writer into BufferedWriter

The Java application below shows you how to convert an Writer object into a BufferedWriter object.

ConvertToBufferedWriter.java

import org.apache.commons.io.IOUtils;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class ConvertToBufferedWriter {
    public static void main(String... args) {
        try {
            Writer writer = new FileWriter("D:\\Data\\data.txt");

            BufferedWriter bufferedWriter = IOUtils.buffer(writer);
            bufferedWriter.write("Simple Solution");
            IOUtils.close(bufferedWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

After executing the Java program above, a new file was created at D:\Data\data.txt with the content as below. CODE

D:\Data\data.txt

Simple Solution

Happy Coding 😊