Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java DataInputStream readInt() Method

In this tutorial, we will learn about the readInt() method of DataInputStream class in Java. This method is used to read four input bytes of data value and return an integer value.

It reads the next four bytes from the input stream and interprets them into integer type. 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 integer value interpreted from the next four bytes of the current input stream.

public final int readInt() throws IOException

Example: Read Integer using DataInputStream in Java

In this example, we are implementing the readInt() method to read the integer type of data from the file. Here, we will run the loop till the data is available in the file, once the data is not available in the file, we will stop reading data from the file.

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\\output.txt"); 
		DataInputStream dataInputStream = new DataInputStream(inputStream); 
		while(dataInputStream.available()>0)
		{	           
            System.out.print(" "+dataInputStream.readInt());  
        }  
	}  
}


1 2 3 4 5

file //output.txt

1 2 3 4 5

Example 2: Read Integer data using DataInputStream in Java

Here, we are reading the data from the file using the readInt() method, this example is the same as the one mentioned above but we changed the file from where we will read the data. . The data contains in the sample file is present in the file given below:

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); 
		while(dataInputStream.available()>0)
		{	           
            System.out.print(" "+dataInputStream.readInt());  
        }  
	}  
}


10 20 30 40 50

file.txt

10 20 30 40 50

Conclusion

In this tutorial, we learned about the read() method of DataInputStream class in Java, which reads the next four bytes of the data value from the current input stream, and returns it as an integers value. It must be accessed using class objects only, as, trying to access it with class name will throw an IOException.