Search code examples
multithreadingprogress-barjavafx-8fileoutputstream

ProgressBar in Javafx shows only state 0 and 100% while copying file


How to fix this code using multithreading? It's working but I need to know how to add a thread to this code, I think that this is why the progress bar not updating progressively!

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!!");
         }


     }

Can you please post any solution, which helps me?

Thanks for all advices.


Solution

  • There is an example of associating a progress bar with progress of a concurrent task in 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();