Java.io.DataInputStream.readFully() Method
Description
The java.io.DataInputStream.readFully(byte[] b) method reads len bytes from an input stream.
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, int off, int len) method:
public final void readFully(byte[] b, int off, int len)
Parameters
b - the destination buffer.
off - the offset into the data.
len - the number of bytes to read.
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, int off, int len) 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, 4, 5);
// for each byte in the buffer
for (byte b:buf)
{
char c = '0';
if(b!=0)
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 will 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:
0000Hello000