这可能有点晚,但我最近一直在一些地方,我需要知道,有一直读取的字节数,而不是有多少是留下被读取,如这个问题问。但是你可以从我得到的解决方案中得到这个数字。我想知道读取的字节数量,以便我可以监视下载的进度(以防它花了一段时间)。
我最初只是使用DataInputStream#readFully()来下载文件。
buffer = new byte[length];
in.readFully(buffer);
但有时我被留下等待50的任何地方 - 60秒下载完成,这取决于大小。我想实时更新事情的进展情况,所以我改为使用常规的DataInputStream#read(byte [] b,int off,int len)。所以在最后告诉我是一个有的System.out每当我跨越过一个个百分点:
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 + "%");
}
}
知道有多少字节要被读取,一些小的修改可到最后的例子进行说明。有一个跟踪变量来代替我的百分比,例如:
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()'。我同意'CountingInputStream',但这看起来很丑陋(至少对我来说)。 – 2010-07-24 13:48:41
我明白你的观点,但我不认为这很丑陋。这样的类相当有用,并且绝对可重用,在FileConnections之外的其他情况下也是如此。即使它稍微丑陋,它也被封装并存放在一个小班中。 – aioobe 2010-07-25 09:04:16