Java Program to create Stream from a String/Byte Array

Java 8Object Oriented ProgrammingProgramming

Create an input stream and set the string:

DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream("pqrs tu v wxy z".getBytes()));

The getBytes() method is used to convert a string into sequence of bytes and returns an array of bytes.

Now return one single input byte:

(char) inputStream.readByte()

Example

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
public class Demo {
public static void main(String[] args) throws Exception {
   DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream("pqrs tu v wxy z".getBytes()));
      System.out.print((char) inputStream.readByte());
      System.out.print((char) inputStream.readByte());
      inputStream.close();
   }
}

Output

Pq
raja
Published on 25-Apr-2019 16:25:10
Advertisements