search

Home  >  Q&A  >  body text

java stringwriter 的 flush()问题

我想知道我在第20行对sw字符串输出流进行了刷新,那为什么21行还会有输出?

天蓬老师天蓬老师2822 days ago657

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-17 11:37:44

    StringWriter implements the flush method just because its parent class Writer implements the Flushable interface,
    If you can see the source code, you will find that StringWriter actually does nothing:

        /**
         * Flush the stream.
         */
        public void flush() {
        }
    

    The flush method affects the destination buffer and allows it to be output directly to the destination,
    StringWriter operates memory directly and has no destination, so the flush method is meaningless for it.

    You can use sw.getBuffer().setLength(0) to achieve this, but it will not reduce the length of the character array stored inside the buffer, it will just write the content as ‘’, so the best way is to create a new StringWriter object.

    reply
    0
  • Cancelreply