Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Null OutputStream in Java?

People also ask

What is OutputStream in Java?

The Java. io. OutputStream class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.

Do we need to close OutputStream in Java?

Close an OutputStreamOnce you are done writing data to a Java OutputStream you should close it.

What is difference between OutputStream and FileOutputStream?

Outputstream is an abstract class whereas FileOutputStream is the child class. It's possible that you could use Outputstream to just write in bytes for a prexisting file instead of outputting a file.

How do you write OutputStream in Java?

Methods of OutputStreamwrite() - writes the specified byte to the output stream. write(byte[] array) - writes the bytes from the specified array to the output stream. flush() - forces to write all data present in output stream to the destination. close() - closes the output stream.


/**Writes to nowhere*/
public class NullOutputStream extends OutputStream {
  @Override
  public void write(int b) throws IOException {
  }
}

Java doesn't it would seem but Apache Commons IO does. Take a look at the following:

https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/output/NullOutputStream.html

Hope that helps.


It's not mentioned yet, so I'll also add Guava's ByteStreams.nullOutputStream(), as some might prefer Guava over Apache Commons IO or already have it in their project.

Note: If you use an older version of Guava (from 1.0 to 13.0), you want to use com.google.io.NullOutputStream.


Since Java 11, there is a static utility that does exactly what you need, a static factory method OutputStream.nullOutputStream():

Returns a new OutputStream which discards all bytes. The returned stream is initially open. The stream is closed by calling the close() method. Subsequent calls to close() have no effect.


Rehashing the answers already provided -

Java does not have a NullOutputStream class. You could however roll your own OutputStream that ignores any data written to it - in other words write(int b), write(byte[] b) and write(byte[] b, int off, int len) will have empty method bodies. This is what the Common IO NullOutputStream class does.


No, but it is pretty easy to implement.

See this question "How to remove System.out.println from codebase"

And then you just have to:

System.setOut( DevNull.out );

Or something like that :)

System.setOut(PrintStream)


Java 11 added OutputStream.nullOutputStream()