Convert an Input Stream to a String in Java
This post will discuss how to convert an input stream to a string in Java.
There are several ways to convert an input stream to a string in Java, depending on the version of Java we are using and the libraries we have available. Here are some of the most common methods:
1. Using BufferedReader
class
This is a low-level approach that reads bytes from the input character stream and decodes them into characters using a specified charset. The idea is to use the efficient BufferedReader class to read text from the InputStream
by wrapping a BufferedReader
around InputStreamReader
. The characters are then appended to a StringBuilder object, which can be converted to a String. Here’s an example of this approach:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.io.*; import java.nio.charset.StandardCharsets; class Main { public static String getString(InputStream in) throws IOException { Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append('\n'); } br.close(); return sb.toString(); } public static void main(String[] args) throws IOException { byte[] bytes = "Techie Delight".getBytes(StandardCharsets.UTF_8); InputStream in = new ByteArrayInputStream(bytes); System.out.println(getString(in)); // Techie Delight in.close(); } } |
We can also use the Java 8 Stream API to process the input stream. The idea is to can use the lines()
method of BufferedReader
to read each line from the InputStream
as a Stream
, and then use the Collectors.joining()
method to join them into a single String. Here’s an example of how we can achieve this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.*; import java.nio.charset.StandardCharsets; import java.util.stream.Collectors; class Main { public static String getString(InputStream in) { return new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); } public static void main(String[] args) throws IOException { byte[] bytes = "Techie Delight".getBytes(StandardCharsets.UTF_8); InputStream in = new ByteArrayInputStream(bytes); System.out.println(getString(in)); // Techie Delight in.close(); } } |
2. Using Scanner
class
The Scanner class can scan text from various sources, including InputStreams
. We can use a delimiter to specify how to split the input into tokens, and then use the next()
method to get the next token as a String. The default delimiter is whitespace, but we can change it to any regular expression. We can use the beginning of the input or the end of the input as a delimiter. To illustrate, consider the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Scanner; class Main { public static String getString(InputStream in) throws IOException { return new Scanner(in, StandardCharsets.UTF_8.toString()) .useDelimiter("\\z") // `\z` represents the end of the input .next(); } public static void main(String[] args) throws IOException { byte[] bytes = "Techie Delight".getBytes(StandardCharsets.UTF_8); InputStream in = new ByteArrayInputStream(bytes); System.out.println(getString(in)); // Techie Delight in.close(); } } |
3. Using Guava Library
Another option is to use the third party libraries that provide utility methods to convert an InputStream
to a String, such as Google Guava. The CharStreams class by Guava provides the toString()
method that can read all characters from a Readable
object and returns them as a String
. The idea is to get a Readable
object from the input stream, so can convert it to string. We can do so by wrapping an InputStream
with an InputStreamReader
. Here is the code demonstrating this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import com.google.common.io.CharStreams; import java.io.*; import java.nio.charset.StandardCharsets; class Main { public static String getString(InputStream in) throws IOException { InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8.toString()); return CharStreams.toString(isr); } public static void main(String[] args) throws IOException { byte[] bytes = "Techie Delight".getBytes(StandardCharsets.UTF_8); InputStream in = new ByteArrayInputStream(bytes); System.out.println(getString(in)); // Techie Delight in.close(); } } |
4. Using Apache Commons IO
Like Guava, IOUtils class by Apache Commons IO provides the toString()
method which can directly get the contents of an InputStream
as a string using the specified character encoding. We can also use the IOUtils.copy()
method that copies bytes from an InputStream
to chars on a Writer
using the specified character encoding. These methods offers better performance and error handling than the plain Java methods. Here is an example of using these methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import org.apache.commons.io.IOUtils; import java.io.*; import java.nio.charset.StandardCharsets; class Main { public static String getString1(InputStream in) throws IOException { return IOUtils.toString(in, StandardCharsets.UTF_8.toString()); } public static String getString2(InputStream in) throws IOException { Writer writer = new StringWriter(); IOUtils.copy(in, writer, StandardCharsets.UTF_8.toString()); return writer.toString(); } public static void main(String[] args) throws IOException { byte[] bytes = "Techie Delight".getBytes(StandardCharsets.UTF_8); InputStream in = new ByteArrayInputStream(bytes); System.out.println(getString1(in)); // Techie Delight in.close(); in = new ByteArrayInputStream(bytes); System.out.println(getString2(in)); // Techie Delight in.close(); } } |
That’s all about converting an input stream to a string in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)