In this article, we will take a look at how to how to convert InputStream to string in Java.We will look at the options to convert it using JDK and also with the help of third party APIs.While working on the file system, converting InputStream to String is a common task.
1. Convert InputStream To String In Java 8
Java 8 provides a lot of new feature and Stream API is one of them. We can use this new API to convert the InputStream to String.Here is a quick example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.stream.Collectors;
public class ConvertStreamToString {
public static void main(String[] args) throws IOException {
URI content = URI.create("https://www.google.com/"); // Quick way to get input steam
/**
* Convert the stream in to String using Java 8 Stream API
*/
String output = new BufferedReader(
new InputStreamReader(content.toURL().openStream()))
.lines().collect(Collectors.joining()); //you can use the joiner based on your requirement like joining("/n")
System.out.println(output); //<!doctype html>
2. Convert InputStream To String In Java 9
Java 9 provides a convenient readAllBytes
method on the InputStream
. We can use this method to for stream to String conversion.
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ConvertStreamToString {
public static void main(String[] args) throws IOException {
InputStream stream = new ByteArrayInputStream("Convert Stream to String using Java 9".getBytes());
String output = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(output); //Convert Stream to String using Java 9
}
}
3. Apache Common
One of the clean ways to Convert InputStream to String in Java is using Apache Commons IOUtils.
public class InputStreamStringCommonIO {
public static void main(String[] args) throws IOException {
String sampleTestString = "Converting input stream to String using Apache Common IO";
InputStream inputStream = new ByteArrayInputStream(sampleTestString.getBytes());
convertUsingCopy(inputStream, StandardCharsets.UTF_8);
convertUsingToString(inputStream, StandardCharsets.UTF_8);
}
public static void convertUsingCopy(final InputStream inputStream, final Charset inputEncoding) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, inputEncoding);
System.out.println(writer.toString());
}
public static void convertUsingToString(final InputStream inputStream, final Charset inputEncoding) throws IOException {
String output = IOUtils.toString(inputStream, inputEncoding);
System.out.println(output);
}
}
Output
Converting input stream to String using Apache Common IO
Just note that IOUtils.toString()
method does not close inputStream, you can use IOUtils.closeQuietly()
to close it.Most of the modern project use Apache Commons as de-facto API, if you are using Apache Commons IO, this is your best option.
4. Java Way
If you do not have the option to use Apache Commons IO or Java 8 and higher version, there are multiple ways to Convert InputStream to String in Java.
4.1 Convert InputStream to String InputStreamReader and StringBuilder
public class ConvertByInputStreamReader {
public static void main(String[] args) {
String sampleTestString = "Converting input stream to String using JDK Input Stream Reader";
InputStream inputStream = new ByteArrayInputStream(sampleTestString.getBytes());
System.out.println(inputStream);
}
private static String getStringByInputStreamReader(final InputStream inputStream) throws IOException {
final int bufferSize = 1024;
final char[] buffer = new char[bufferSize];
final StringBuilder output = new StringBuilder();
Reader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
int character = 0;
while ((character = streamReader.read(buffer, 0, buffer.length)) > 0) {
output.append(buffer, 0, character);
}
return output.toString();
}
}
4.2 Convert InputStream to String BufferReader and StringBuilder
public class ReadUsingBufferReader {
public static void main(String[] args) {
String sampleTestString = "Converting input stream to String using JDK Buffer Reader";
InputStream inputStream = new ByteArrayInputStream(sampleTestString.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder outStream = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
outStream.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(outStream.toString());
}
}
Output
Converting input stream to String using JDK Buffer Reader
4.3 Convert InputStream to String Using Scanner
public class ReadUsingScanner {
public static void main(String[] args) {
String sampleTestString = "Converting input stream to String using JDK Using Scanner";
InputStream inputStream = new ByteArrayInputStream(sampleTestString.getBytes());
Scanner inputScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name()).useDelimiter("\\A");
String output = inputScanner.hasNext() ? inputScanner.next() : "";
System.out.println(output);
inputScanner.close();
}
}
Output
Converting input stream to String using JDK Using Scanner
Summary
In this article we saw the different options to convert InputStream to String in Java. If you are using Java 8 or higher version, you can always use the new stream API to do this. For old Java version my recommendation is to use the Apache Commons IO. The source code is available Over on Github.
DataInputStream consumes less amount of memory space being it is binary stream, where as BufferedReader consumes more memory space being it is character stream.