java - 如何在下载中获取每秒字节数?

标签 java

<分区>

我想知道如何在下载中获得每秒的字节数
这是我到目前为止得到的:

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;
    }
}    

关于java - 如何在下载中获取每秒字节数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37975260/

相关文章:

java - 为什么 DatagramSocket 不通过网络发送多播地址?

java - 消息不确定是什么

Java 多部分帖子

java - SINGLE_TABLE @Inheritance 不继承的 EclipseLink JPA 问题

java udf 添加列

java - Bouncy CasSTLe CMS 公钥加密

java - 将两个泛型类型添加到另一个类型中

java - 使用 SNMP4J 加载 MIB

java - 按字符串或索引的一部分对字符串数组进行排序?

java - 如何获取日期和时区格式