BufferedInputStream read(byte[], int, int) in Java

read(byte[], int, int): This method is available in java.io.BufferedInputStream class of Java.

Syntax:

int java.io.BufferedInputStream.read(byte[] b, int off, int len) throws IOException

This method takes three arguments. This method reads bytes from this byte-input stream into the specified byte array, starting at the given offset.

This iterated read continues until one of the following conditions becomes true

1. The specified number of bytes has been read.

2. The read method of the underlying stream returns -1, indicating end-of-file.

3. The available method of the underlying stream returns zero, indicating that further input requests would block.

Note:

If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1. Otherwise, this method returns the number of bytes actually read.

Parameters: Three parameters are required for this method.

b: destination buffer.

off: offset at which to start storing bytes.

len: maximum number of bytes to read.

Returns: the number of bytes read, or -1 if the end of the stream has been reached.

Throws:

IOException - if this input stream has been closed by invoking its close() method,or an I/O error occurs.

Approach 1: When no exception

Java

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

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

        InputStream inputStream = InputStream.nullInputStream();
        BufferedInputStream bufferedInputStream =
new BufferedInputStream(inputStream);

        byte b[] = { 1, 1, 2, 3 };

        int off = 0, len = 2;

        System.out.println(bufferedInputStream.read(b, off, len));
    }
}

Output:

-1


Approach 2: When IOException

Java

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

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

        InputStream inputStream = InputStream.nullInputStream();
        BufferedInputStream bufferedInputStream =
new BufferedInputStream(inputStream);

        byte b[] = { 1, 1, 2, 3 };

        int off = 0, len = 2;

        bufferedInputStream.close();

        System.out.println(bufferedInputStream.read(b, off, len));
    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:168) at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:334)


No comments:

Post a Comment