這可能有點晚,但我最近一直在一些地方,我需要知道,有一直讀取的字節數,而不是有多少是留下被讀取,如這個問題問。但是你可以從我得到的解決方案中得到這個數字。我想知道讀取的字節數量,以便我可以監視下載的進度(以防它花了一段時間)。
我最初只是使用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