It may be a little late, but I recently worked on something where I needed to know the number of bytes read, as opposed to how much was left to read, as asked by this question. But you can get this number from the solution that I have. I wanted to know the number of bytes read so that I could track the progress of the download (in case it took some time).
At first, I just used DataInputStream # readFully () to load files.
buffer = new byte[length]; in.readFully(buffer);
But sometimes I was left to wait from 50 to 60 seconds to complete the download, depending on the size. I wanted to get real-time updates on how everything happens, so I changed to using just the usual DataInputStream # read (byte [] b, int off, int len). So, there System.out is there at the end telling me whenever I jumped a percentage point:
buffer = new byte[length]; int totalRead = 0; int percentage = 0; while (totalRead < length) { int bytesRead = in.read(buffer, totalRead, (length - totalRead)); if (bytesRead < 0) throw new IOException("Data stream ended prematurely"); totalRead += bytesRead; double progress = ((totalRead*1.0) / length) * 100; if ((int)progress > percentage) { percentage = (int)progress; System.out.println("Downloading: " + percentage + "%"); } }
To find out how many bytes are left to read, some minor changes can be made to the last example. Having a tracker variable instead of my percentage, for example:
buffer = new byte[length]; int totalRead = 0; int bytesLeft= 0; while (totalRead < length) { bytesLeft = length - totalRead; int bytesRead = in.read(buffer, totalRead, bytesLeft); if (bytesRead < 0) throw new IOException("Data stream ended prematurely"); totalRead += bytesRead; System.out.println("Bytes left to read: " + bytesLeft); }
source share