Search code examples
javaandroiddataoutputstream

Progress of dataOutputStream.readFully


I'm receiving a file using dataInputStream.readFully, so i'd like to show the progress of the transmision. Is it possible to know the progress of readFully method? Thank you.


Solution

  • No - the whole point is that it's a single call to make it simpler to read.

    If you want to read more gradually (e.g. to update a progress bar) you can just read a chunk at a time with InputStream.read(byte[], int, int) in a loop until you've read all the data. For example:

    byte[] data = new byte[bytesToRead];
    int offset = 0;
    int bytesRead;
    while ((bytesRead = stream.read(data, offset, data.length - offset)) > -1) {
        offset += bytesRead;
        // Update progress indicator
    }
    

    This is just like the JDK 8 code for readFully, but with progress indication in the loop.