Is there a Null OutputStream in Java?

前端 未结 11 605
灰色年华
灰色年华 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:43

    ByteArrayOutputStream is what you want (assuming that the API will be outputting text). Just instantiate a new one.

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

    I believe that this is what you're looking for, I was looking for the same thing: This is for redirecting output streams from standard error, standard out in ProcessBuilder objects.

    Blockquote

    pb.redirectError( ProcessBuilder.Redirect.appendTo( new File( "NUL:" ) ) );
    
    • Dom
    0 讨论(0)
  • 2020-12-08 13:51

    There is new boy in the town, that takes care of this like a charm, just few lines of code should work. Its JDK 11 and nullWriter() has been introduced there, that takes care of this. Here goes the code to deal with same old problem, new way without worrying about Operating System(OS).

    String fileContent = "Welcome to StackOverflow readers !! Here goes the question link...";
    Writer writer = Writer.nullWriter();
    writer.write(fileContent);
    writer.close();
    

    Hope this may help someone!

    0 讨论(0)
  • 2020-12-08 13:53
    /**Writes to nowhere*/
    public class NullOutputStream extends OutputStream {
      @Override
      public void write(int b) throws IOException {
      }
    }
    
    0 讨论(0)
  • 2020-12-08 13:54

    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.

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