Convert InputStream into BufferedInputStream in Java using Apache Commons IO

Tags: Convert IOUtils Apache Commons Apache Commons IO InputStream FileInputStream BufferedInputStream

In this Java tutorial we learn how to use the IOUtils utility class in Apache Commons IO to convert an InputStream object into a BufferedInputStream 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 InputStream into BufferedInputStream

For example, we have the data.txt file at D:\Data\data.txt with the content as below.

Simple Solution

The application below reads the above text file into an InputStream object and then converts it to a BufferedInputStream object.

ConvertToBufferedInputStream.java

import org.apache.commons.io.IOUtils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;

public class ConvertToBufferedInputStream {
    public static void main(String... args) {
        try {
            InputStream inputStream = new FileInputStream("D:\\Data\\data.txt");

            BufferedInputStream bufferedInputStream = IOUtils.buffer(inputStream);
            int value;
            while((value = bufferedInputStream.read()) != IOUtils.EOF) {
                System.out.print((char)value);
            }
            IOUtils.close(bufferedInputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Simple Solution

Happy Coding 😊