Site icon

Convert InputStream to String in Java

Methods of InputStreamReader used for inputStream to String conversion

Method Name Description
InputStreamReader(InputStream in,Charset cs) Creates an InputStreamReader that uses the given charset.
int read(char[] cbuf, int offset, int length) Reads characters into a portion of an array

Algorithm: convert InputStream to String in java

  1. Create inputSteam from dummy String.
  2. Create StringBuilder instance to store stream buffer
  3. Read input stream till reach end of file
  4. Append the read buffer to StringBuilder
  5. Convert StringBuilder to String
  6. Print the output String.

Code: convert InputStream to String – InputStreamReader java

package org.learn;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class InputStreamToString {

    public static void main(String[] args) throws IOException {

        InputStream inputStream = getInputStream();

        char[] buffer = new char[1024];
        StringBuilder builder = new StringBuilder();

        try(Reader in = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
            int ch;
            while ((ch = in.read(buffer, 0, buffer.length)) > 0) {
                builder.append(buffer, 0, ch);
            }
        }
        System.out.println("InputStream to String output is:");
        System.out.println(builder.toString());
    }

    private static InputStream getInputStream () {
        String dummyString = "Java.io.InputStream class is the superclass of \r\n" +
                "all classes representing an input stream of bytes.";

        return new ByteArrayInputStream(dummyString.getBytes());
    }
}

Output: convert InputStream to String in Java

InputStream to String output is:
Java.io.InputStream class is the superclass of 
all classes representing an input stream of bytes.
Exit mobile version