目前,我有下面的代碼讀取位於網絡上的文件,並將其寫入一個文件在手機上:可以確定要下載的文件的大小?
InputStream inputStream = new URL(sourceFileWebAddress).openStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
int count;
byte buffer[] = new byte[1024];
while ((count = bufferedInputStream.read(buffer, 0, buffer.length)) != -1)
fileOutputStream.write(buffer, 0, count);
有誰知道是否有可能(使用上述設置或以其他方式),以確定在開始下載之前要讀取的字節總數(爲了在下載過程中向用戶發佈百分比進度)?
此外,如果服務器不支持該內容或由於某種原因文件大小未知,內容長度可能爲-1。 –
警告:'url.openConnection()。getContentLength()'將執行GET,而不是'HEAD'。請參閱下面Santosh的回答以獲得更好的方法(即,在調用getContentLength()之前執行'connection.setRequestMethod(「HEAD」)')。 –