如何更新进度条的进度以显示复制文件的进度

时间:2014-08-25 14:35:34

标签: file javafx progress-bar file-transfer

我想要一个进度条来指示要复制的文件
如何通过组合下面的代码行来更新进度条以显示复制文件的进度?

这是我的进度条代码。

@FXML
private void startbtnaction(ActionEvent event) {
    startbtn.setDisable(true);
    progressbar.setProgress(0);
    txt.setText("");
    cancelbtn.setDisable(false);
    copyworker = createWorker(numFiles);

    progressbar.progressProperty().unbind();
    progressbar.progressProperty().bind(copyworker.progressProperty());
    progressindicator.progressProperty().unbind();
    progressindicator.progressProperty().bind(copyworker.progressProperty());

         copyworker.messageProperty().addListener(new ChangeListener<String>(){

                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                    txt.setText(newValue+"\n");
                }  
            });
        new Thread(copyworker).start();

}
 private Task createWorker(int numFiles) {
   return new Task(){

       @Override
       protected Object call() throws Exception {
           for (int i = 0; i < numFiles; i++) {
               long elapsedtime=System.currentTimeMillis();
               copyFile("somefile", "some dest file");
               elapsedtime=System.currentTimeMillis()-elapsedtime;
               String status=elapsedtime+"milliseconds";

               updateMessage(status);
               updateProgress(i+1, numFiles);

           }
           return true;

       }

   };
}

 public  void copyFile(String src,String dest)throws InterruptedException{
     Random rnd=new Random(System.currentTimeMillis());
    long millis=rnd.nextInt(1000);
    Thread.sleep(millis);

 }

/// //////////////////////////////////////////// ///////////////////////////////////

这是我的文件复制代码..

InputStream istream = RemoteInputStreamClient.wrap(sendappcontent);
    BufferedInputStream bis = new BufferedInputStream(istream);

    //downloaded file...
    File file = new File("D:\\SERVER\\Temp\\" + contentfile.getName());//server saving point

    if (!file.exists()) {
        file.createNewFile();
    }

    FileOutputStream fileOutputStream = new FileOutputStream(file);
    FileChannel channel = fileOutputStream.getChannel();


    byte b[] = new byte[1024];
    long startTime = System.currentTimeMillis();
    while (bis.available() > 0) {
        bis.read(b);
        System.out.println("B");
        System.out.println((System.currentTimeMillis() - startTime) / 1000);
        ByteBuffer buffer = ByteBuffer.wrap(b);
        channel.write(buffer);
    }

    bis.close();
    fileOutputStream.flush();
    channel.close();
    fileOutputStream.close();

    System.out.println("done");

0 个答案:

没有答案