How to convert String to InputStream in Java

  • 14 October 2016
  • ADM

 

How to convert String to InputStream in Java - images/logos/java.jpg

 

To convert String to InputStream, in Java, you can use ByteArrayInputStream classes.

Example

package com.admfactory.io;

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

public class StringToInputStream {

    public static void main(String[] args) {

	String str = "This is a random text message.";

	/** Convert String to InputStream */
	InputStream is = new ByteArrayInputStream(str.getBytes());

	System.out.println("Testing String to InputStream");
	System.out.println();

	/** Read the InputStream  and display to the console */
	BufferedReader br = new BufferedReader(new InputStreamReader(is));
	String line;
	try {
	    while ((line = br.readLine()) != null) {
		System.out.println(line);
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    /** finally block to close the {@link BufferedReader} */
	    if (br != null) {
		try {
		    br.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	}
    }
}

Output

Testing String to InputStream

This is a random text message.

 

References