How to convert a String to an InputStream object in Java?n

A ByteArrayInputStream is a subclass of InputStream class and it contains an internal buffer that contains bytes that may be read from the stream. We can convert a String to an InputStream object by using the ByteArrayInputStream class. This class constructor takes the string byte array which can be done by calling the getBytes() method of a String class.


public class StringToInputStreamTest {
   public static void main(String []args) throws Exception {
      String str = "Welcome to TutorialsPoint";
      InputStream input = getInputStream(str, "UTF-8");
      int i;
      while ((i = > -1) {
         System.out.print((char) i);
   public static InputStream getInputStream(String str, String encoding) throws          UnsupportedEncodingException {
      return new ByteArrayInputStream(str.getBytes(encoding));


Welcome to TutorialsPoint