user35443
user35443

Reputation: 6413

Does FilterOutpuStream perform write normally or not?

Oracle documentation says:

write(byte[] b, int off, int len) throws IOException

Writes len bytes from the specified byte array starting at offset off to this output stream. The write method of FilterOutputStream calls the write method of one argument on each byte to output.

Note that this method does not call the write method of its underlying input stream with the same arguments. Subclasses of FilterOutputStream should provide a more efficient implementation of this method.

I have two questions:

  1. On this page I found code that uses FilterOutputStream for decoration of FileOutputStream, and writes normal output to file. Why is FilterOutputStream calling write() method of underlying stream on each byte, when it's able to call same overload on underlying stream and make operation faster?
  2. Why is underlying stream input stream?

Thanks.

Upvotes: 2

Views: 99

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502716

  1. I believe the point is that if you want a very simple filter, you can just override the write(int) method, and know that everything will pass through that. It will be inefficient, but work. So if you wanted a stream which filtered out every even byte, you could do that easily:

    public class OddByteOutputStream extends FilterOutputStream
    {
        public OddByteOutputStream(OutputStream output)
        {
            super(output);
        }
    
        @Override
        public void write(int b)
        {
            if ((b & 1) == 1)
            {
                out.write(b);
            }
        }
    }
    

    An alternative approach would have been to make write(byte[]) delegate, but make write(int) and write(byte[], int, int) abstract, to force subclasses to work out how to handle the calls reasonably efficiently.

  2. This is just a typo, I suspect.

Upvotes: 3

Related Questions