Javafx中的ProgressBar在复制文件时仅显示状态0和100%

时间:2016-02-19 03:14:31

标签: multithreading progress-bar javafx-8 fileoutputstream

如何使用多线程修复此代码? 它工作但我需要知道如何为这段代码添加一个线程,我认为这就是为什么进度条不会逐步更新!

public void copyfile(ActionEvent event){

         try {

                    File fileIn = new File(filepath);
                    long length = fileIn.length();
                    long counter = 0;
                    double r;
                    double res=(counter/length);

                    filename=fieldname.getText();

                    FileInputStream from=new FileInputStream(filepath);
                    FileOutputStream to=new FileOutputStream("C:\\xampp\\htdocs\\videos\\"+filename+".mp4");
                    byte [] buffer = new byte[4096];
                    int bytesRead=0;

                    while( (r=bytesRead=from.read(buffer))!= 1){

                    progressbar.setProgress(counter/length);
                          counter += r*100;  

                    to.write(buffer, 0, bytesRead);

                    System.out.println("File is loading!!"+(counter/length));

         }

         from.close();
         to.close();
     } catch (Exception e) {
         progress.setText("upload is finished!!");
         }


     }

请你发布任何解决方案,这对我有帮助吗?

感谢所有建议。

1 个答案:

答案 0 :(得分:1)

有一个示例将进度条与Oracle's JavaFX 8 concurrency documentation中的并发任务的进度相关联。

import javafx.concurrent.Task;

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i=1; i<=max; i++) {
            if (isCancelled()) {
               break;
            }
            updateProgress(i, max);
        }
        return null;
    }
};
ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();