Reading a file in Java is pretty simple, we simply can use FileInputStream to read the contents of a file, but if you want to do some operations on the content which is read such as validation, pattern matching, etc, then it would be easier to perform on the String rather than the InputStream. In this article, we will see the different ways to convert InputStream to String in Java. We will be using the Native Java and Third party libraries like Apache Commons IO and Guava.
9 Different ways to convert InputStream to String in Java?
1. Convert InputStream to String using BufferedReader
This is the easiest way to convert InputStream to String and well known to almost all the Java developers.
- Read the content of the file using the InputStream
- Pass the inputStream to the constructor of InputStreamReader instance and pass InputStreamReader to the constructor of the BufferedReader
- Append each line of the file returned by the bufferedReader to the StringBuilder object
package com.javainterviewpoint; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class InputStreamToString { public static void main(String[] args) { InputStream inputStream = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = new StringBuilder(); String text; try { inputStream = new FileInputStream (new File("D:\\temp.txt")); bufferedReader = new BufferedReader (new InputStreamReader(inputStream)); while ((text = bufferedReader.readLine()) != null ) { stringBuilder.append(text); } System.out.println(stringBuilder); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Output:
Convert InputStream to String with BufferedReader
2. Convert using Scanner
- Read the content of the file using the InputStream
- The InputStream instance and the charset (UTF-8) is passed to the constructor of the Scanner
- We have used the delimiter as “\\n” so that the scanner reads line by line.
- Append each line of the file returned by the scanner.next() to the StringBuilder object
package com.javainterviewpoint; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class InputStreamToString { public static void main(String[] args) { InputStream inputStream = null; Scanner scanner = null; StringBuilder stringBuilder = new StringBuilder(); try { inputStream = new FileInputStream (new File("D:\\temp.txt")); scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\n"); while (scanner.hasNext()) { stringBuilder.append(scanner.next()); } System.out.println(stringBuilder); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
3. Using Stream API Collect
- InputStream reads the file, pass the inputStreamReader instance to the constructor of the BufferedReader
- BufferedReader returns a stream and it is converted into a String using the joining() method of Collectors Class
- The collect() method collect together the desired results into a result container such as a Collection and the joining() method joins various elements of a character or string array into a single String object
package com.javainterviewpoint; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Collectors; public class InputStreamToString { public static void main(String[] args) { InputStream inputStream = null; try { inputStream = new FileInputStream (new File("D:\\temp.txt")); String result = new BufferedReader(new InputStreamReader(inputStream)).lines() .collect(Collectors.joining("\n")); System.out.println(result); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
4. Using parallel
We have additionally added parallel() to the above code, Parallel Streams give us the flexibility to iterate in a parallel pattern, but it has its equal performance impacts as each sub-stream is a single thread running and acting on the data, it has overhead compared to the sequential stream
package com.javainterviewpoint; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Collectors; public class InputStreamToString { public static void main(String[] args) { InputStream inputStream = null; try { inputStream = new FileInputStream (new File("D:\\temp.txt")); String result = new BufferedReader(new InputStreamReader(inputStream)).lines() .parallel().collect(Collectors.joining("\n")); System.out.println(result); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
5. Using ByteArrayOutputStream
- Read the input file using InputStream and Create an instance for ByteArrayOutputStream.
- The read() method returns the next byte of data and returns -1 when it is the end of the stream, read the content using a while loop till the end of the stream
- Now call the write() method on top of the byteArrayOutputStream instance passing the buffer byte.
package com.javainterviewpoint; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class InputStreamToString { public static void main(String[] args) { InputStream inputStream = null; try { inputStream = new FileInputStream (new File("D:\\temp.txt")); ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer= new byte[512]; while ((inputStream.read(buffer)) != -1) { result.write(buffer); } System.out.println(result); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
6. Using IOUtils toString
Apache Commons provides the IOUtils class to read content from a file. In order to use the commons-io (Apache Commons) library, we need to add the below maven dependency
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
We will be using toString() and copy() method of IOUtils class to Convert InputStream to String
Using the toString() of Apache Commons is pretty simple. The toString() method reads data from a stream, all we need to do is that read the file using inputStream and pass it to the toString() method along with the Charset.
package com.javainterviewpoint; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; public class InputStreamToString { public static void main(String[] args) { InputStream inputStream = null; try { inputStream = new FileInputStream (new File("D:\\temp.txt")); String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8); System.out.println(result); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
7. Using IOUtils Copy
The copy() method copies all the data from one stream to another, the content of the inputStream will be copied to the StringWriter.
package com.javainterviewpoint; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; public class InputStreamToString { public static void main(String[] args) { InputStream inputStream = null; try { inputStream = new FileInputStream (new File("D:\\temp.txt")); StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8); System.out.println(writer.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
8. Using Guava CharStreams
Let’s now look at the way to convert InputStream to String using Guava Library. Guava is the Google core libraries for Java.
In order to use the Guava library, we need to add the below dependency
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
CharStreams class proides utility methods for working with character streams. The toString() method of CharStreams class, reads all characters from a Readable object into a String. We need to pass inputStreamReader instance and Charset to the toString().
package com.javainterviewpoint; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import com.google.common.io.CharStreams; public class InputStreamToString { public static void main(String[] args) { InputStream inputStream = null; try { inputStream = new FileInputStream (new File("D:\\temp.txt")); String result = CharStreams.toString(new InputStreamReader( inputStream, StandardCharsets.UTF_8)); System.out.println(result); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
9. Using Guava ByteSource
- ByteSource class is an immutable supplier of InputStream instances. The openStream() method opens a new InputStream for reading from this source.
- We will be overriding the openStream() method to use the inputStream which we have created to read the input file.
- Now view ByteSource as a CharSource with a UTF8 charset using the asCharSource() method.
- Use the read() method to read the CharSource as String.
package com.javainterviewpoint; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import com.google.common.io.ByteSource; public class InputStreamToString { public static void main(String[] args) { try { InputStream inputStream = new FileInputStream (new File("D:\\temp.txt")); ByteSource byteSource = new ByteSource() { @Override public InputStream openStream() throws IOException { return inputStream; } }; String result = byteSource.asCharSource(StandardCharsets.UTF_8).read(); System.out.println(result); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Happy Learning !! 🙂
Do let me know if you come across any new methodology to convert InputStream to String.
Leave a Reply