Convert String to InputStream in Java

 Posted On  | Yashwant Chavan 

Below example demonstrate how to convert String to InputStream. It uses ByteArrayInputStream to converts into InputStream, Which is used to represent an input stream of bytes.

byte[] java.lang.String.getBytes() Encodes String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. new ByteArrayInputStream() Creates a ByteArrayInputStream from byte array.

Using ByteArrayInputStream

package com.technicalkeeda.app;

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

public class StringToInputStreamExample {
    public static void main(String[] args) {
        try {
            String string = "hello";

            InputStream is = new ByteArrayInputStream(string.getBytes());
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

hello


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0352 seconds.