Java DataInputStream read() Method

In this tutorial, we will learn about the read() method of DataInputStream class in Java. The work of this method is to read the bytes from the current input stream and store them in the buffer byte array. It is a non-static method, available in the java.io package and can be accessed only with a class object, trying to invoke it with the class name will result in an error.

Syntax

This is the syntax of this method. It accepts b as a parameter, which is the byte buffer array, into which the data is to be read from this stream.

public final int read(byte[] b) throws IOException  

It returns the actual number of bytes read in the integer form, and -1 if the end of the stream is reached.

Example: Read Data DataInputStream in Java

In this example, we are reading the data from the file using the read() method, after reading the data from the file this method will copy the data to the passed byte array and return the integer value indicating that the number of bytes read from the file. In this example, we read the 18 bytes.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		FileInputStream inputStream  = new FileInputStream("E:\\studytonight\\file.txt"); 
		DataInputStream dataInputStream = new DataInputStream(inputStream); 
		int count = inputStream.available(); 
		byte[] byte_arr = new byte[count]; 
		int bytes = dataInputStream.read(byte_arr); 
		System.out.println("Total bytes: "+bytes); 
		for (byte b : byte_arr)
		{ 
			System.out.print((char)b); 
		} 
	}  
}


Total bytes: 18
Hello Studytonight

Example 2: Read Data using DataInputStream in Java

Here, we are implementing another overloading method of the read() method, here instead of the reading whole data from the document we can slice the data by passing offset meaning the start pointer from where it will start the reading and the length of the data to be read.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		FileInputStream inputStream  = new FileInputStream("E:\\studytonight\\file.txt"); 
		DataInputStream dataInputStream = new DataInputStream(inputStream); 
		int count = inputStream.available(); 
		byte[] byte_arr = new byte[count]; 
		int bytes = dataInputStream.read(byte_arr, 0, 5); 
		System.out.println("Total bytes: "+bytes); 
		for (byte b : byte_arr)
		{ 
			System.out.print((char)b); 
		} 
	}  
}


Total bytes: 5
Hello

Conclusion

In this tutorial, we learned about the read() method of DataInputStream class in Java which is used to read the bytes from the current input stream and store them in the buffer byte array. It returns the actual number of bytes read in the integer form, and -1 if the end of the stream is reached and no more data is available to read.