BufferedInputStream transferTo(OutputStream) in Java

transferTo(OutputStream): This method is available in the java.io.BufferedInputStream class of Java.

Syntax:

long java.io.InputStream.transferTo(OutputStream out) throws IOException

This method takes one argument. This method reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read.

Parameters: One parameter is required for this method.

out: the output stream, non-null.

Returns: the number of bytes transferred.

Throws:

1. IOException - if an I/O error occurs when reading or writing.

2. NullPointerException - if out is null.

Approach 1: When no exception

Java

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

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

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

        System.out.println(bufferedInputStream.transferTo(System.out));
    }
}

0


Approach 2: IOException 

Java

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

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

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

        bufferedInputStream.close();
        System.out.println(bufferedInputStream.transferTo(System.out));
    }
}

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.transferTo(InputStream.java:776)


Approach 3: NullPointerException

Java

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

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

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

        System.out.println(bufferedInputStream.transferTo(null));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: out at java.base/java.util.Objects.requireNonNull(Objects.java:233) at java.base/java.io.InputStream.transferTo(InputStream.java:772)


No comments:

Post a Comment