• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

9 Different ways to Convert InputStream to String in Java?

May 28, 2019 by javainterviewpoint Leave a Comment

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?

Convert InputStream to String

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.

Other interesting articles which you may like …

  • JavaScript HMAC SHA256 Hash Example
  • JavaScript SHA256 Hash Example
  • ChaCha20 Poly1305 Encryption and Decryption
  • ChaCha20 Encryption and Decryption
  • RSA Encryption and Decryption
  • AES 256 Encryption and Decryption
  • AES 128 Encryption and Decryption
  • Java URL Encode and Decode Example
  • Java Salted Password Hashing
  • Google Tink Example – Google Cryptography
  • Constructor in Java
  • Private Constructors in Java
  • Java Constructor Chaining with example
  • Java – Constructor in an Interface?
  • Constructor.newInstance() method
  • Parameterized Constructor in Java
  • Java 8 – Lambda Expressions
  • Java 8 – ForEach Example
  • Java 8 Default Methods in Interface
  • Multiple Inheritance in Java 8 through Interface
  • Java 9 – jdeprscan
  • Private Methods in Interfaces Java 9
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serialization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: Core Java, Java Tagged With: Convert InputStream to String, Input Stream to String, InputStream to String

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·