This may be a bit late, but I've recently been working on something where I needed to know the amount of bytes that have been read, as opposed to how many are left to be read, as this question asks. But you can derive that number from the solution that I've got. I wanted to know the amount of bytes read so I could monitor the download's progress (in case it took a while).
I was initially just using DataInputStream#readFully() to download the files.
buffer = new byte[length];
in.readFully(buffer);
But sometimes I was left waiting for anywhere from 50 - 60 seconds for the download to complete, depending on the size. I wanted to get real-time updates on how things were going, so I changed to use just the regular DataInputStream#read(byte[] b, int off, int len). So there's a System.out there at the end telling me whenever I've 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 know how many bytes remain to be read, some minor modifications can be made to the last example. Having a tracker variable in place 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);
}
fileSize()
. I agree aboutCountingInputStream
, but this looks ugly (at least to me). – Atrice