我想知道如何在下载中获得每秒的字节数。
这是我到目前为止得到的:
while ((count = in.read(data, 0, byteSize)) > -1) {
downloaded += count;
fout.write(data, 0, count);
output.setText(formatFileSize(downloaded) + "/ " + formatFileSize(fileLength));
// perSecond.setText(formatFileSize((long) speed)+"/s");
progressbar.setValue((int) downloaded);
if (downloaded >= fileLength) {
System.out.println("Done!");
JOptionPane.showMessageDialog(frame, "Done!", "Info", 1);
progressbar.setValue(0);
output.setText("");
perSecond.setText("");
return;
}
我该怎么做呢?
一个选择是创建一个更新您的 UI 的 DownloadProgressTask 类。
示例:
class DownloadProgressTask extends TimerTask
{
// I'm not sure what types these guys are so change them accordingly
private Object output;
private Object progressbar;
private long fileLength = 0;
private AtomicLong downloaded = new AtomicLong();
public DownloadProgressTask (Object output, Object progressbar, long fileLength)
{
this.output = output;
this.progressbar = progressbar;
this.fileLength = fileLength;
}
// Do your task here
public void run()
{
int downloadedInt = (int) downloaded.get();
output.setText(formatFileSize(downloadedInt) + "/ " + formatFileSize(fileLength));
// perSecond.setText(formatFileSize((long) speed)+"/s");
progressbar.setValue(downloadedInt);
}
public void updateDownloaded (long newVal)
{
downloaded.set(newVal);
}
}
然后您将在开始读取文件的 while 循环之前安排此任务:
示例:
// Create Timer Object
Timer time = new Timer();
// Create the download task
DownloadProgressTask dt = new DownloadProgressTask(output, progressbar, fileLength);
// schedule task to run now and every 1 second thereafter
time.schedule(dt, 0, 1000);
现在,您的 while 循环看起来像这样:
while ((count = in.read(data, 0, byteSize)) > -1) {
downloaded += count;
fout.write(data, 0, count);
// let the task know the update
dt.updateDownloaded(downloaded);
if (downloaded >= fileLength) {
// cancel the task here
dt.cancel();
System.out.println("Done!");
JOptionPane.showMessageDialog(frame, "Done!", "Info", 1);
progressbar.setValue(0);
output.setText("");
perSecond.setText("");
return;
}
}