0

クライアントからサーバーにファイルを転送しています。転送にかかる時間はわかりません。しかし、私の UI は、ユーザーへの通知がなくても同じままです。ファイルがアップロードされるまで進行状況が続くように、進行状況バーを維持する必要があります。どうすればこれを達成できますか。

私は.netでこのシナリオを知っています。しかし、どのようにJavaでそれを行うことができますか?

4

2 に答える 2

4

トラッシュゴッドの答えは、真に「不確定」なアクションに対して正しいです。ファイル転送がこのカテゴリに当てはまる理由は何だと思いますか? なんらかのプログレス バーが関連付けられたファイルをインターネットでダウンロードしたことはありませんか? それがないことを想像できますか?

How do I use JProgressBar to display file copy progress? への回答の中で提供されている以下の例を参照してください。

public OutputStream loadFile(URL remoteFile, JProgressBar progress) throws IOException
{
    URLConnection connection = remoteFile.openConnection(); //connect to remote file
    InputStream inputStream = connection.getInputStream(); //get stream to read file

    int length = connection.getContentLength(); //find out how long the file is, any good webserver should provide this info
    int current = 0;

    progress.setMaximum(length); //we're going to get this many bytes
    progress.setValue(0); //we've gotten 0 bytes so far

    ByteArrayOutputStream out = new ByteArrayOutputStream(); //create our output steam to build the file here

    byte[] buffer = new byte[1024];
    int bytesRead = 0;

    while((bytesRead = inputStream.read(buffer)) != -1) //keep filling the buffer until we get to the end of the file 
    {   
        out.write(buffer, current, bytesRead); //write the buffer to the file offset = current, length = bytesRead
        current += bytesRead; //we've progressed a little so update current
        progress.setValue(current); //tell progress how far we are
    }
    inputStream.close(); //close our stream

    return out;
}
于 2012-07-05T03:24:26.417 に答える
2

How to Use Progress Barsに示されているように、進行状況を測定するのに十分なデータが得られるまで、またはダウンロードが完了するまで、不確定モードを指定できます。正確な実装は、転送がどのように行われるかによって異なります。理想的には、送信者が最初に長さを提供しますが、データが蓄積するにつれて速度を動的に計算することも可能です。

于 2012-07-05T03:19:53.067 に答える