2016-06-22 6 views
2

私はどのようにしてバイトをダウンロードで入手できるか知りたいと思います。ここ
は、私がこれまでに得たものである:ダウンロードでバイト/秒を取得するにはどうすればよいですか?

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

[System.currentTimeMillis()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--)を使用してください。 「1秒あたりのバイト数」とは、文字通り「バイト数を経過秒で割ったもの」を意味します。 – VGR

答えて

-1

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 ((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; 
    } 
}  
関連する問題