Java.io.DataInputStream.readFully() Method

Advertisements


Description

The java.io.DataInputStream.readFully(byte[] b) method reads bytes from an input stream and allocates those into the buffer array b.

It blocks until the one of the below conditions occurs:

  • b.length bytes of input data are available.
  • End of file detected.
  • If any I/O error occurs.

Declaration

Following is the declaration for java.io.DataInputStream.readFully(byte[] b) method:

public final void readFully(byte[] b)

Parameters

  • NA

Return Value

This method does not return any value.

Exception

  • IOException -- if any I/O error occurs or the stream has been closed.

  • EOFException -- if this input stream reaches the end before.

Example

The following example shows the usage of java.io.DataInputStream.readFully(byte[] b) method.

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataInputStreamDemo {
   public static void main(String[] args) throws IOException {
      
      InputStream is = null;
      DataInputStream dis = null;
      
      try{
         // create file input stream
         is = new FileInputStream("c:\\test.txt");
         
         // create new data input stream
         dis = new DataInputStream(is);
         
         // available stream to be read
         int length = dis.available();
         
         // create buffer
         byte[] buf = new byte[length];
         
         // read the full data into the buffer
         dis.readFully(buf);
         
         // for each byte in the buffer
         for (byte b:buf)
         {
            // convert byte to char
            char c = (char)b; 
            
            // prints character
            System.out.print(c);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }finally{
         
         // releases all system resources from the streams
         if(is!=null)
            is.close();
         if(dis!=null)
            dis.close();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

Hello World!

Let us compile and run the above program, this will produce the following result:

Hello World!



Advertisements
Advertisements