DataInputStream read(byte[]) in Java

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

Syntax:

int java.io.DataInputStream.read(byte[] b) throws IOException

This method takes three arguments. This method reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.

Note This method blocks until input data are available, the end of the file is detected, or an exception is thrown.

If b is null, a NullPointerException is thrown.

Parameters: One parameter is required for this method.

b: the buffer into which the data is read.

Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

Throws:

1. IOException - if the first byte cannot be read for any reason other than the end of the file, the stream has been closed and the underlying input stream does not support reading after close, or another I/O error occurs.

2. NullPointerException: If b is null.

Approach 1: When no exception

Java

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

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

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

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

        dataInputStream.close();
    }
}

Output:

2


 Approach 2: NullPointerException

Java

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

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

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

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

        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.read(DataInputStream.java:99)


No comments:

Post a Comment