Java DataInputStream readFully() Method
In this tutorial, we will learn about the readFully()
method of DataInputStream class in Java. This method is used to read bytes equal to the length of the specified byte array, from the current input stream, and store them into the specified byte array.
It is a non-static method, available in the java.io package.
Syntax
This is the syntax of this method. It accepts one parameter, the specified byte array, into which the data is to be read. It does not return any value.
public final void readFully(byte[] b) throws IOException
Example: Read Byte Array using DataInputStream in Java
In this example, we are reading the data from the file using the readFully() 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];
dataInputStream.readFully(byte_arr);
for (byte b : byte_arr)
{
System.out.print((char)b);
}
}
}
Hello Studytonight
Example 2: Read Byte Array using DataInputStream in Java
Here, we are implementing overloading method of the readFully() method, 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];
dataInputStream.readFully(byte_arr, 0, 5);
for (byte b : byte_arr)
{
System.out.print((char)b);
}
}
}
Hello
Conclusion
In this tutorial, we learned about the readFully()
method of DataInputStream class in Java, which reads the bytes equal to the length of the specified byte array, from the given input stream, and stores them into the same. It must be accessed with the class object only and if we try to access the method with the class name then we will get an error.