javabufferedoutputstream

Obtain the number of written bytes from BufferedOutputStream


I am wondering if BufferedOutputStream offers any way to provide the count of bytes it has written. I am porting code from C# to Java. The code uses Stream.Position to obtain the count of written bytes.

Could anyone shed some light on this? This is not a huge deal because I can easily add a few lines of code to track the count. It would be nice if BufferedOutputStream already has the function.


Solution

  • For text there is a LineNumberReader, but no counting the progress of an OutputStream. You can add that with a wrapper class, a FilterOutputStream.

    public class CountingOutputStream extends FilterOutputStream {
        
        private long count;
        private int bufferCount;
        
        public CountingOutputStream(OutputStream out) {
            super(out);
        }
        
        public long written() {
            return count;
        }
        
        public long willBeWritten() {
            return count + bufferCount;
        }
        
        @Override
        public void flush() {
            count += bufferCount;
            bufferCount = 0;
            super.flush();
        }
    
        public void write​(int b)
               throws IOException {
            ++bufferCount;
            super.write(b);     
        }
        @Override
        public void write(byte[] b, int off, int len)
               throws IOException {
            bufferCount += len;
            super.write(b, off, len);
        }
        
        @Override
        public void write(byte[] b, int off, int len)
               throws IOException {
            bufferCount += len;
            super.write(b, off, len);
        }
    }
    

    One could also think using a MemoryMappedByteBuffer (a memory mapped file) for a better speed/memory behavior. Created from a RandomAccessFile or FileChannel.

    If all is too circumstantial, use the Files class which has many utilities, like copy. It uses Path - a generalisation of (disk I/O) File -, for files from the internet, files inside zip files, class path resources and so on.