亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何跟蹤 FileOutputStream 的下載量?

如何跟蹤 FileOutputStream 的下載量?

一只萌萌小番薯 2023-07-28 16:51:22
假設我有以下代碼將從我的網站下載一些內容。URL website = new URL(url);ReadableByteChannel rbc = Channels.newChannel(website.openStream());FileOutputStream fos = new FileOutputStream("something.zip");fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);fos.close();我想制作一個 JProgressBar 來顯示正在下載的文件的進度。為了實現這一目標,我知道一種方法是獲取文件的總大小和文件當前下載的字節數,然后獲取百分比。下面是獲取文件大小的代碼:HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("HEAD");long fileSize = conn.getContentLengthLong();但是,獲取 FileOutputStream 的下載字節很困難,因為您必須創建循環來跟蹤當前正在下載的字節。那么你怎樣才能實現這一目標呢?注意:該算法應該適用于非常大的文件,因為我從互聯網下載的文件大小為 1 GB。
查看完整描述

1 回答

?
青春有我

TA貢獻1784條經驗 獲得超8個贊

我在下面提供了代碼片段,您可以查看它?;旧希仨氂嬎阕止潝?,然后通過深入到 100 得出某個百分比來進行計算。


InputStream inputStream = util.getInputStream();

? ? ? ? ? ? // opens an output stream to save into file

? ? ? ? ? ? FileOutputStream outputStream = new FileOutputStream(saveFilePath);


? ? ? ? ? ? byte[] buffer = new byte[BUFFER_SIZE];

? ? ? ? ? ? int bytesRead = -1;

? ? ? ? ? ? long totalBytesRead = 0;

? ? ? ? ? ? int percentCompleted = 0;

? ? ? ? ? ? long fileSize = util.getContentLength();


? ? ? ? ? ? while ((bytesRead = inputStream.read(buffer)) != -1) {

? ? ? ? ? ? ? ? outputStream.write(buffer, 0, bytesRead);

? ? ? ? ? ? ? ? totalBytesRead += bytesRead;

? ? ? ? ? ? ? ? percentCompleted = (int) (totalBytesRead * 100 / fileSize);


? ? ? ? ? ? ? ? setProgress(percentCompleted); ?

查看完整回答
反對 回復 2023-07-28
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號