Java NullOutputStream-class And Method Code Example


Here is an example of using the NullOutputStream class from the org.apache.commons.io package in Java to create an OutputStream that discards all data written to it:

import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.output.NullOutputStream;

public class NullOutputStreamExample {
    public static void main(String[] args) throws IOException {
        // Create a NullOutputStream
        OutputStream nos = new NullOutputStream();

        // Write to the NullOutputStream
        nos.write("Hello World!".getBytes());
        // Nothing will be written to the NullOutputStream
        // Close the NullOutputStream
        nos.close();
    }
}

In this example, a NullOutputStream is created and used to write the string "Hello World!" to it, but nothing will be written to the output stream.

This class is useful when you need to discard the data being written to an output stream, for example, when you want to discard the output of a command that is executed using a Process object, or when you want to write to an output stream, but you don't want to keep the data.

It can also be used in situations where you want to measure how long it takes to write to an output stream, but you don't actually want to keep the data.