Java InputStream to String example shows how to convert InputStream to String in Java. The example also shows various ways to convert InputStream to String.
How to convert InputStream to String in Java?
There are various ways to convert InputStream to String as given below.
1) Using BufferedReader and InputStreamReader classes
Create BufferedReader from InputStream using InputStreamReader. Read the contents line by line from BufferedReader and append the lines to StringBuilder. Once done, convert StringBuilder to String using the toString
method.
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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
package com.javacodeexamples.ioexamples; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class InputStreamToStringExample { public static void main(String[] args) { InputStream is = null; try{ //create InputStream from file is = new FileInputStream("C:/dir_1/data.txt"); String str = convertInputStreamToString(is); System.out.println(str); }catch(IOException ioe){ ioe.printStackTrace(); }finally{ try{ if(is != null) is.close(); }catch(Exception e){ e.printStackTrace(); } } } /* * Method to convert InputStream to String */ private static String convertInputStreamToString(InputStream is) { BufferedReader br = null; StringBuilder sbContent = new StringBuilder(); try{ /* * Create BufferedReader from InputStreamReader */ br = new BufferedReader(new InputStreamReader(is)); /* * read line by line and append content to * StringBuilder */ String strLine = null; boolean isFirstLine = true; while( (strLine = br.readLine()) != null){ if(isFirstLine) sbContent.append(strLine); else sbContent.append("\n").append(strLine); /* * Flag to make sure we don't append new line * before the first line. */ isFirstLine = false; } }catch(IOException ioe){ ioe.printStackTrace(); }finally{ try{ if(br != null) br.close(); }catch(Exception e){ e.printStackTrace(); } } //convert StringBuilder to String and return return sbContent.toString(); } } |
Output
1 2 3 |
File content line 1 File content line 2 File content line 3 |
Note: This approach converts “\r” or “\r\n” new line characters to “\n”.
2) Using ByteArrayOutputStream and InputStream read method
In this approach, we are going to read the stream into a byte buffer and then write the buffer to the ByteArrayOutputStream. Once all the bytes are read from the stream, we will convert it to String using toString
method.
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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
/* * Method to convert InputStream to String */ private static String convertInputStreamToString(InputStream is) { String strResult = null; //create ByteArrayOutputStream ByteArrayOutputStream bos = new ByteArrayOutputStream(); try{ //create buffer to hold bytes read from stream byte[] buffer = new byte[1024]; /* * Read bytes from InputStream to buffer * until there are no more bytes */ int size; while((size = is.read(buffer)) != -1){ //write buffer to the ByteArrayOutputStream bos.write(buffer, 0, size); } //convert ByteArrayOutputStream to String using UTF-8 Character Set strResult = bos.toString( StandardCharsets.UTF_8.name()); }catch(IOException ioe){ ioe.printStackTrace(); }finally{ try{ if(bos != null) bos.close(); }catch(Exception e){ e.printStackTrace(); } } return strResult; } |
3) Using ByteArrayOutputStream and BufferedInputStream classes
This approach is similar to the previous approach with one difference. We are going to use the BufferedInputStream instead of reading bytes directly from the InputStream to the byte array buffer.
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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
/* * Method to convert InputStream to String */ private static String convertInputStreamToString(InputStream is) { String strResult = null; ByteArrayOutputStream bos = null; BufferedInputStream bis = null; try{ //create ByteArrayOutputStream bos = new ByteArrayOutputStream(); //create BufferedInputStream from InputStream bis = new BufferedInputStream(is); int byteValue; while( (byteValue = bis.read()) != -1 ){ bos.write(byteValue); } //convert ByteArrayOutputStream to String using UTF-8 Character Set strResult = bos.toString( StandardCharsets.UTF_8.name()); }catch(IOException ioe){ ioe.printStackTrace(); }finally{ try{ if(bos != null) bos.close(); }catch(Exception e){ e.printStackTrace(); } try{ if(bis != null) bis.close(); }catch(Exception e){ e.printStackTrace(); } } return strResult; } |
4) Using Scanner class
This approach uses the Scanner class to read from InputStream till the end of the text by providing the “\A” pattern which matches the start of the string.
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 25 26 27 28 29 30 31 32 |
/* * Method to convert InputStream to String */ private static String convertInputStreamToString(InputStream is) { String strResult = null; Scanner scanner = null; try{ //create scanner from InputStream scanner = new Scanner(is); //set scanner delimiter as beginning of the content scanner.useDelimiter("\\A"); //get the token - this will return whole content as single token if( scanner.hasNext() ) strResult = scanner.next(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(scanner != null) scanner.close(); }catch(Exception e){ e.printStackTrace(); } } return strResult; } |
5) Using Apache Commons IOUtils toString method
It is an absolute breeze to convert the input stream to String if you use the IOUtils class from the Apache Commons library as given below.
1 2 3 4 5 6 7 8 |
/* * Method to convert InputStream to String */ private static String convertInputStreamToString(InputStream is) throws IOException { String strResult = IOUtils.toString(is, Charset.forName("UTF-8")); return strResult; } |
It could not be easier than this. Supply input stream and the character set in the arguments and it’s done.
6) Using Apache Commons IOUtils copy method
This approach uses IOUtil’s copy
method to write an input stream to the StringWriter object and then converting the StringWriter to String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/* * Method to convert InputStream to String */ private static String convertInputStreamToString(InputStream is) throws IOException { //create StringWriter object StringWriter strWriter = new StringWriter(); /* * Use copy method of StringUtils class to * copy input stream to StringWriter. * * Make sure to use method version which * accepts character set. */ IOUtils.copy(is, strWriter, Charset.forName("UTF-8")); //convert StringWriter to String and return return strWriter.toString(); } |
7) Using Java 8 Streams
Finally, If you are using Java 8 or later versions, you can use Streams to achieve the same as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* * Method to convert InputStream to String */ private static String convertInputStreamToString(InputStream is) throws IOException { //Create BufferedReader from the input stream BufferedReader br = new BufferedReader(new InputStreamReader(is)); //read lines separated by new line and join them again using \n String strResult = br.lines().collect(Collectors.joining("\n")); return null; } |
Note: This approach converts line breaks to “\n”.
What is the suggested way to convert InputStream to String?
Approach 1 and 7 convert “\r\n” and “\r” to “\n” which may not be desired in a particular use case. Approach 2, 3, and 5 are suggested as they should run faster as compared to other approaches.
This example is a part of Java String tutorial.
Refer to all File examples to learn more.
Please let me know your views in the comments section below.