Thursday, September 4, 2025
HomeLanguagesJavaDataInputStream readByte() method in Java with Examples

DataInputStream readByte() method in Java with Examples

The readByte() method of DataInputStream class in Java is used to read and return one input byte. The byte is a signed value in the range from -128 to +127. The bytes in this method are read from the accommodated input stream.

Syntax:

public final byte readByte()
                  throws IOException

Specified By: This method is specified by readByte() method of DataInput interface.

Parameters: This method does not accept any parameter.

Return value: This method returns the byte value read. It is a signed 8-bit byte.

Exceptions:

  • EOFException – It throws EOFException if the input stream is ended.
  • IOException – This method throws IOException if the stream is closed or some other I/O error occurs.

Below programs illustrate readByte() method in DataInputStream class in IO package:

Program 1:




// Java program to illustrate
// DataInputStream readByte() method
import java.io.*;
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
  
        // Create byte array
        byte[] b = { 10, 20, 30, 40, 50 };
  
        // Create byte array input stream
        ByteArrayInputStream byteArrayInputStr
            = new ByteArrayInputStream(b);
  
        // Convert byte array input stream to
        // DataInputStream
        DataInputStream dataInputStr
            = new DataInputStream(
                byteArrayInputStr);
  
        while (dataInputStr.available() > 0) {
            // Print bytes
            System.out.println(
                dataInputStr.readByte());
        }
    }
}


Output:

10
20
30
40
50

Program 2:




// Java program to illustrate
// DataInputStream readByte() method
import java.io.*;
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
  
        // Create byte array
        byte[] b = { -20, -10, 0, 10, 20 };
  
        // Create byte array input stream
        ByteArrayInputStream byteArrayInputStr
            = new ByteArrayInputStream(b);
  
        // Convert byte array input stream to
        // DataInputStream
        DataInputStream dataInputStr
            = new DataInputStream(
                byteArrayInputStr);
  
        while (dataInputStr.available() > 0) {
            // Print bytes
            System.out.println(
                dataInputStr.readByte());
        }
    }
}


Output:

-20
-10
0
10
20

References:
https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#readByte()

RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS