0

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.

Hong
  • 17,643
  • 21
  • 81
  • 142

1 Answers1

1

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Thanks a lot for the elucidation. – Hong Sep 23 '22 at 13:52
  • What of ```bufferCount``` when the enclosed stream *cannot* be written to? – g00se Sep 23 '22 at 14:38
  • @g00se that is why I count it separately, otherwise 100% would be no guarantee anything (the buffer) was written to disk. On an IOException for the wrapped stream it is irrelevant how much is till waiting in the buffer for writing. Then it is irrelevant whether bufferCount is added to the total or not. Keeping apart also better tells how much could be written. – Joop Eggen Sep 23 '22 at 14:47
  • 1
    Yes, I see. Actually I had to do a double-take on those void writing methods. I guess it's because I'm far more used to looking at and overriding ```read``` methods which return values ;) – g00se Sep 23 '22 at 15:02