Learn to convert an InputStream to a String using BufferedReader
, Scanner
or IOUtils
classes.
Reading a String from InputStream is a very common requirement in several types of applications where we have to read a file from a network stream or from a file system.
1. Using InputStream.readAllBytes() (Since Java 9)
The InputStream.readAllBytes()
API converts the input stream to bytes. Then we use the new String()
to create a new String
object.
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
String fileContent = new String( in.readAllBytes() );
Internally, it uses readNBytes(Integer.MAX_VALUE) method. It means it should not be used to read a file size greater than 2GB.
2. Using BufferedReader
Using BufferedReader is the easiest and most popular way to read a file into String. It helps to read the file as InputStream and process it line by line.
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
String fileContent = out.toString();
reader.close();
Alternatively, we can use the BufferedReader.lines() method [added in Java 8] to get the Stream of lines and process the content as needed.
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
String newLine = System.getProperty("line.separator");
String fileContent;
try (Stream<String> lines = new BufferedReader(new InputStreamReader(in)).lines()) {
fileContent = lines.collect(Collectors.joining(newLine));
}
//Use fileContent
3. Google Guava IO
Guava library has some very useful classes and methods to perform IO operations. These classes hide all complexities, otherwise exposed.
3.1. Dependencies
Maven dependency for Google Guava.
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
3.2. Using ByteSource
ByteSource
represents a readable source of bytes, such as a file. It has utility methods that are typically implemented by opening a stream, doing something, and finally closing the stream that was opened.
Its asCharSource(charset)
method decodes the bytes read from a source as characters in the given Charset. It returns the characters as String as the method output.
InputStream inputStream = new FileInputStream(new File("C:/temp/test.txt"));
ByteSource byteSource = new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return inputStream;
}
};
String fileContent = byteSource
.asCharSource(Charsets.UTF_8)
.read();
3.3. Using CharStreams
The CharStreams
class also provides utility methods for working with character streams. Using InputStreamReader
along with CharStreams
helps in converting an InputStream
to a String
.
Java program to convert InputStream to String with CharStreams class in Google guava library.
InputStream inputStream = new FileInputStream(new File("C:/temp/test.txt"));
String fileContent = null;
try (final Reader reader = new InputStreamReader(inputStream)) {
fileContent = CharStreams.toString(reader);
}
System.out.println(fileContent);
4. Apache Commons IO
4.1. Dependencies
Include the following dependencies in the project to include common-io jars.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
4.2. Using IOUtils
Apache commons has a very useful class IOUtils to read file content into String. It makes the code a lot cleaner and easy to read. It provides better performance too.
Use either of the two methods-
IOUtils.copy()
IOUtils.toString()
//Method 1 IOUtils.copy()
StringWriter writer = new StringWriter();
IOUtils.copy(new FileInputStream(new File("C:/temp/test.txt")), writer, "UTF-8");
String fileContent = writer.toString();
System.out.println(fileContent);
//Method 2 IOUtils.toString()
String fileContent = IOUtils.toString(new FileInputStream(new File("C:/temp/test.txt")), "UTF-8");
System.out.println(fileContent);
5. Java InputStream to String using Scanner
Using Scanner class is not so popular, but it works. The reason it works is because Scanner
iterates over tokens in the stream, and in this process, we can separate tokens using the “beginning of the input boundary” thus giving us only one token for the entire contents of the stream.
FileInputStream fin = new FileInputStream(new File("C:/temp/test.txt")); java.util.Scanner scanner = new java.util.Scanner(fin,"UTF-8").useDelimiter("\A"); String fileContent = scanner.hasNext() ? scanner.next() : ""; scanner.close();
That’s all. The purpose of this post is to provide quick links for a very specific purpose i.e. to read InputStream into String.
Happy Learning !!
Comments