Java – Convert String to InputStream

java-logoHow to convert String to InputStream? Sometimes we need to pass String as InputStream, here we will see how to converted it.

 

Objective:

How to convert Java String object to InputStream object?

Environment & Tools:

  • Eclipse
  • Java JDK

( 1 ) Convert String to InputStream

InputStream inputStream = new ByteArrayInputStream("Hello String".getBytes());

( 2 ) Convert InputStream Back to String

This is one way to convert InputStream to String for other ways check this post

package com.hmkcode;

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[]){
		
		InputStream inputStream = new ByteArrayInputStream("Hello String".getBytes());
		
		
		// Just to test our inputstream
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		try {
			
			System.out.println(reader.readLine());
			
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}