Is there a Null OutputStream in Java?

前端 未结 11 604
灰色年华
灰色年华 2020-12-08 13:04

I need to specify an OutputStream for an API I\'m using, but I don\'t actually have a need for the output. Does Java have an OutputStream equivale

相关标签:
11条回答
  • 2020-12-08 13:30

    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.

    0 讨论(0)
  • 2020-12-08 13:31

    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.

    0 讨论(0)
  • 2020-12-08 13:32

    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.

    0 讨论(0)
  • 2020-12-08 13:32

    Java 11 added OutputStream.nullOutputStream()

    0 讨论(0)
  • 2020-12-08 13:40

    Not in the standard library AFAIK, but it shouldn't be difficult to create one by overriding write in OutputStream

    0 讨论(0)
  • 2020-12-08 13:41

    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)

    0 讨论(0)
提交回复
热议问题