我想知道如何在下载中获得每秒字节 这是我到目前为止所得到的:
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;
}
我到底该怎么做?
答案 0 :(得分:-1)
一个选项是创建一个更新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;
}
}