BufferedInputStream readAllBytes() in Java

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

Syntax:

byte[] java.io.InputStream.readAllBytes() throws IOException

This method reads all remaining bytes from the input stream. This method blocks until all remaining bytes have been read and the end of the stream is detected, or an exception is thrown.

Note: This method does not close the input stream.

Parameters: NA

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

Throws:

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

2. 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 BufferedInputStreamreadAllBytes {
    public static void main(String[] args) throws IOException {

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

        System.out.println(Arrays.toString(bufferedInputStream.readAllBytes()));
    }
}

[]


Approach 2: IOException 

Java

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

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

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

        bufferedInputStream.close();
        System.out.println(Arrays.toString(bufferedInputStream.readAllBytes()));
    }
}

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) at java.base/java.io.InputStream.readAllBytes(InputStream.java:346)


No comments:

Post a Comment