Java NullInputStream-class And Method Code Example


Here is an example of how to use the NullInputStream class from the Apache Commons IO library in Java:

import java.io.IOException;
import org.apache.commons.io.input.NullInputStream;

class Example {
    public static void main(String[] args) {
        try (NullInputStream nis = new NullInputStream(10)) {
            byte[] buffer = new byte[1024];
            int bytesRead = nis.read(buffer);
            System.out.println("Bytes read: " + bytesRead); // 0
        } catch (IOException e) {
            // handle exception
        }
    }
}

This code creates a NullInputStream with a size of 10 bytes. The NullInputStream is an input stream that discards any data read from it and always returns -1 when read.

In this example, it read from the NullInputStream using the read method, it returns -1, since it's an empty input stream.

It can be used to test code that requires an InputStream, or when you want to discard data from an InputStream but don't want to modify the original code.

You can also use the NullInputStream with a size of -1 to represent an infinite input stream.