Create Stream from a String Byte Array in Java



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
Updated on: 2019-07-30T22:30:25+05:30

549 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements