ObjectInputStream readByte() method in Java with examples

The readByte() method of the ObjectInputStream class in Java is used to read the 8 bit (byte).
Syntax:
public byte readByte()
Parameters: This method does not accept any parameter.
Return Value: This method returns the 8 bit byte read
Errors and Exceptions: The function throws three exceptions which is described below:
- EOFException: The exception is thrown if the end of file is reached.
- IOException: The exception is thrown if an I/O error has occurred.
Below program illustrate the above method:
Program 1:
Java
// Java program to illustrate// the above method  import java.io.*;  public class GFG {      public static void main(String[] args)        throws IOException    {        byte[] array            = { 1, 34, 23,                42, 69, 22 };          try {              // create new byte            // array input stream            InputStream input                = new ByteArrayInputStream(array);              // create data input stream            DataInputStream output                = new DataInputStream(input);              // readBoolean till the            // data available to read            while (output.available() > 0) {                  // read one single byte                byte bt = output.readByte();                  // print the byte                System.out.print(bt + " ");            }        }          catch (Exception ex) {        }    }} |
Output:
Program 2:
Java
// Java program to illustrate// the above method  import java.io.*;  public class GFG {      public static void main(String[] args)        throws IOException    {        byte[] array            = { 'G', 'e', 'e', 'k',                's', 'f', 'o', 'r',                'g', 'e', 'e', 'k',                's' };          try {              // create new byte            // array input stream            InputStream input                = new ByteArrayInputStream(array);              // create data input stream            DataInputStream output                = new DataInputStream(input);              // readBoolean till the            // data available to read            while (output.available() > 0) {                  // read one single byte                byte bt = output.readByte();                  // print the byte                System.out.print(bt + " ");            }            System.out.println();            System.out.println();        }          catch (Exception ex) {        }    }} |
Output:
Reference:
https://docs.oracle.com/javase/10/docs/api/java/io/ObjectInputStream.html#readByte()




