Convert InputStream to Char Array in Java using Apache Commons IO
Tags: Convert Char Array IOUtils Apache Commons Apache Commons IO InputStream FileInputStream
In this Java tutorial, we learn how to read the InputStream object as a char array 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 read InputStream object as a Char Array using IOUtils class
For example, we have a text file at D:\Data\data.txt with content as below.
Simple Solution
Java Tutorials
Apache Commons IO Tutorials
Spring Boot Tutorials
The Java program below, we read the text file into an InputStream object and convert it to a char array using the IOUtils.toCharArray() method.
InputStreamToCharArray.java
import org.apache.commons.io.IOUtils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class InputStreamToCharArray {
public static void main(String... args) {
try {
InputStream inputStream = new FileInputStream("D:\\Data\\data.txt");
char[] data = IOUtils.toCharArray(inputStream, StandardCharsets.UTF_8);
for(char c : data) {
System.out.print(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Simple Solution
Java Tutorials
Apache Commons IO Tutorials
Spring Boot Tutorials
Happy Coding 😊