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


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.

Example

import java.io.*;

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 = input.read()) > -1) {
         System.out.print((char) i);
      }
      System.out.println();
   }
   public static InputStream getInputStream(String str, String encoding) throws UnsupportedEncodingException {
      return new ByteArrayInputStream(str.getBytes(encoding));
   }
}

Output

Welcome to TutorialsPoint
raja
Published on 08-Aug-2019 15:01:53
Advertisements