Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading