Convert InputStream to String in Java

 Posted On  | Yashwant Chavan 

In this tutorial we learn how to convert InputStream into String object using java.

InputStreamReader(InputStream in) - Creates an InputStreamReader from InputStream which uses the default charset.

new BufferedReader(new InputStreamReader(in)) - Creates a buffering character-input stream that uses a default-sized input buffer.

Once you get the BufferedReader object, Read all the data line by line convert into String value.

Using BufferedReader

package com.technicalkeeda.app;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToStringExample {

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

        InputStream in = new ByteArrayInputStream("hello".getBytes());

        BufferedReader reader = new BufferedReader(new InputStreamReader( in ));

        String line = null;
        StringBuilder out = new StringBuilder();

        while ((line = reader.readLine()) != null) {
            out.append(line);
        }

        System.out.println(out.toString());
        reader.close();

    }
}

Output

hello


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0305 seconds.