DataInputStream readFully(byte[]) in Java

readFully(byte[]): This method is available in the java.io.DataInputStream class of Java.

Syntax:

void java.io.DataInputStream.readFully(byte[] b) throws IOException

This method sees the general contract of the readFully method of DataInput. Bytes for this operation are read from the contained input stream.

Parameters: One parameter is required for this method.

b: the buffer into which the data is read.

Returns: NA

Throws:

1. NullPointerException - if b is null.

2. EOFException - if this input stream reaches the end before reading all the bytes.

3. IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.

Approach 1: When no exception

Java

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

public class DataInputStreamreadFully {
    public static void main(String[] args) throws IOException {

        InputStream in = new FileInputStream("hello.txt");
        DataInputStream dataInputStream =
new DataInputStream(in);

        byte b[] = { 'a', 'b', 'c' };
        dataInputStream.readFully(b);
        System.out.println(dataInputStream.readFloat());

        dataInputStream.close();
    }
}

Output:

1.7656148E-19


Approach 2: NullPointerException 

Java

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

public class DataInputStreamreadFully {
    public static void main(String[] args) throws IOException {

        InputStream in = new FileInputStream("hello.txt");
        DataInputStream dataInputStream =
new DataInputStream(in);

        byte b[] = null;
        dataInputStream.readFully(b);
        System.out.println(dataInputStream.readFloat());

        dataInputStream.close();
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "b" is null at java.base/java.io.DataInputStream.readFully(DataInputStream.java:169)


No comments:

Post a Comment