Signup/Sign In

Java DataInputStream readByte() Method

In this tutorial, we will learn about the readByte() method of DataInputStream class in Java. This method is used to read and return a single input byte, which is a signed value in the range of -128 to +127, read from the current input stream.

It is a non-static method, available in the java.io package.

Syntax

This is the syntax of this method. It does not accept any parameter and returns the signed 8-bit byte value read from the current input stream.

public final byte readByte() throws IOException

Example: Read Bytes Array in Java

In this example, we read the data from the byte array using the readByte() method, here it will return the array elements one by one because we are calling this method till the data is available in the DataInputStream.

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
        byte[] byte_arr = { 10, 20, 30, 40, 50 }; 
        ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(byte_arr); 
        DataInputStream dataInputStr = new DataInputStream(byteArrayInputStr);   
        while (dataInputStr.available() > 0) 
        { 
            System.out.println(dataInputStr.readByte()); 
        } 
	}  
}


10
20
30
40
50

Example 2: Read Bytes Array in Java

Here, we are discussing the exception thrown by the DataInputStream when there is no data in the stream or on the other hand we can say the DataInputStream pointer reaches the end of the file then it will throw an exception i.e. EOFException

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
        byte[] byte_arr = {}; 
        ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(byte_arr); 
        DataInputStream dataInputStr = new DataInputStream(byteArrayInputStr);   
        System.out.println(dataInputStr.readByte());          
	}  
}


Exception in thread "main" java.io.EOFException
at java.base/java.io.DataInputStream.readByte(DataInputStream.java:271)

Conclusion

In this tutorial, we learned about the readByte() method of DataInputStream class in Java, which reads and returns the single input byte, which is a signed value in the range -128 to +127.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.