Convert InputStream to String in Java
The InputStream
class is part of the java.io package and represents an ordered sequence of data. InputStreams
are used to read data from files in an orderly fashion. In this tutorial, we will learn different ways to convert an InputStream to a String.
Using InputStreamReader
The InputStreamReader
class provides a convenient read()
method to read data from the InputStream into a character array. We can then convert this char array into a String.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Demo
{
public static String inputStreamToString(InputStream i) throws IOException
{
InputStreamReader isr = new InputStreamReader(i);
char[] charArr = new char[256];
isr.read(charArr);
return new String(charArr);
}
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = inputStreamToString(i);
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
Using InputStreamReader and BufferedReader with StringBuilder
We can use a BufferedReader
to wrap the InputStreamReader
. It increases the overall efficiency of our program. We will use the readLine()
method of BufferedReader
and store the lines in a StringBuilder
object. Finally, we can use the toString()
method on the StringBuilder
to get the string.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Demo
{
public static String inputStreamToString(InputStream i) throws IOException
{
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);//Wrapping InputStreamReader with BufferedReader
String s;
while((s = br.readLine()) != null)
builder.append(s);
return builder.toString();
}
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = inputStreamToString(i);
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
Using InputStreamReader and BufferedReader without StringBuilder
We can simplify the code written in the previous section by using the lines()
method of BufferedReader
. We don't need to use any loops or store the strings in a StringBuilder.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public class Demo
{
public static String inputStreamToString(InputStream i)
{
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = br.lines().collect(Collectors.joining("\n"));
return s;
}
public static void main(String[] args)
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = inputStreamToString(i);
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
}
String from the Input Stream is: hello world
Using the readAllBytes() method of the InputStream
The InputStream
class introduced the readAllBytes()
method in Java 9
. We can use this method to convert an InputStream to a string in just a single line of code. However, it is not recommended to use this approach for reading streams having a large amount of data.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Demo
{
public static String inputStreamToString(InputStream i) throws IOException
{
return new String(i.readAllBytes());
}
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = inputStreamToString(i);
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
Using the Scanner Class
The Scanner
is a well-known class used for reading and parsing data. We can use this class to convert an input stream to a string. We will use the hasNext()
method to check if data exists and the nextLine()
method to read the data from the stream into a StringBuilder
.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class Demo
{
public static String inputStreamToString(InputStream i) throws IOException
{
Scanner scanner = new Scanner(i);
StringBuilder builder = new StringBuilder();
while(scanner.hasNext())
builder.append(scanner.nextLine());
return builder.toString();
}
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = inputStreamToString(i);
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
Using ByteArrayOutputStream
We will use the read()
method to read data from the InputStream
and write it to a byte array. This read() method returns the number of bytes written in the byte array(-1 if no data is written). Then, we will use this byte array to write data into the ByteArrayOutputStream
. Finally, we will use the toString() method to get the string representation.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Demo
{
public static String inputStreamToString(InputStream i) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[128];
int length;
while((length = i.read(buffer)) != -1)
baos.write(buffer, 0, length);
return baos.toString();
}
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = inputStreamToString(i);
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
Using java.nio Package
We can create a new temporary file using java.nio
and copy data from the input stream to this file. Then, we can read the content of this temporary file into a string. Note that a temporary file will be automatically deleted when the program ends.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
public class Demo
{
public static String inputStreamToString(InputStream i) throws IOException
{
Path file = Files.createTempFile(null, null);
Files.copy(i, file, StandardCopyOption.REPLACE_EXISTING);
return new String(Files.readAllBytes(file));
}
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = inputStreamToString(i);
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
Using Google Guava Library
We can use the CharStreams
class of the Guava library to convert an input stream to a string. We will use the toString() method of this class to do this. It will take a Readable object(like the InputStreamReader) and reads the data from it into a string.
package snippet;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.common.io.CharStreams;
public class Demo
{
public static String inputStreamToString(InputStream i) throws IOException
{
try(InputStreamReader isr = new InputStreamReader(i))
{
return CharStreams.toString(isr);
}
}
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = inputStreamToString(i);
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
Using Apache Commons IO
The IOUtils
class of the org.apache.commons.io
package also contains a toString() method. We can directly pass the InputStream object to this method, and it will read the data from it into a string. We also need to specify a Charset.
package snippet;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
public class Demo
{
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
String strFromInputStream = IOUtils.toString(i, StandardCharsets.UTF_8.name());
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
We can also use the StringWriter class of the java.io package and copy the content of the InputStream into the StringWriter. We will use the copy() method of the IOUtils class.
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
public class Demo
{
public static void main(String[] args)
{
try
{
InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
StringWriter sw = new StringWriter();
IOUtils.copy(i, sw, StandardCharsets.UTF_8.name());
String strFromInputStream = sw.toString();
System.out.print("String from the Input Stream is: " + strFromInputStream);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
String from the Input Stream is: hello world
Summary
In this tutorial, we learned the different ways in which we can convert an InputStream to a string. The ByteArrayOutputStream
performs the conversion efficiently and is the recommended approach. We can use the readAllBytes()
method of the InputStream class itself, but it is not recommended for a large amount of data.
The InputStreamReader
is also not favored, as it is quite slow and reads only a single character at a time. We can also use external libraries like the Guava or the Apache Common IO. We also need to handle the exceptions correctly and close the InputStream to avoid resource leaks.