BufferedInputStream readNBytes(int) in Java

readNBytes(int): This method is available in java.io.BufferedInputStream class of Java.

Syntax:

byte[] java.io.InputStream.readNBytes(int len) throws IOException

This method takes one argument. This method reads up to a specified number of bytes from the input stream. This method blocks until the requested number of bytes have been read, the end of stream is detected, or an exception is thrown.

Note: This method does not close the input stream.

Parameters: One parameter is required for this method.

len: the maximum number of bytes to read.

Returns: a byte array containing the bytes read from this input stream.

Throws:

1. IllegalArgumentException - if the length is negative.

2. IOException - if an I/O error occurs.

3. OutOfMemoryError - if an array of the required size cannot be allocated.

Approach 1: When no exception

Java

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

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

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

        int len = 2;

        System.out.println(Arrays.toString(bufferedInputStream.readNBytes(len)));
    }
}

Output:

[]


Approach 2: IllegalArgumentException 

Java

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

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

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

        int len = -2;

        System.out.println(Arrays.toString(bufferedInputStream.readNBytes(len)));
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: len < 0 at java.base/java.io.InputStream.readNBytes(InputStream.java:396)



Approach 3: IOException 

Java

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

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

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

        int len = 2;

        bufferedInputStream.close();

        System.out.println(Arrays.toString(bufferedInputStream.readNBytes(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) at java.base/java.io.InputStream.readNBytes(InputStream.java:409)


No comments:

Post a Comment