Multithreading Javafx中的ProgressBar在复制文件时仅显示状态0和100%
如何使用多线程修复此代码? 它的工作,但我需要知道如何添加一个线程到这段代码,我想这就是为什么进度条没有逐步更新Multithreading Javafx中的ProgressBar在复制文件时仅显示状态0和100%,multithreading,progress-bar,javafx-8,fileoutputstream,Multithreading,Progress Bar,Javafx 8,Fileoutputstream,如何使用多线程修复此代码? 它的工作,但我需要知道如何添加一个线程到这段代码,我想这就是为什么进度条没有逐步更新 public void copyfile(ActionEvent event){ try { File fileIn = new File(filepath); long length = fileIn.length(); long count
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!!");
}
}
你能帮我发布一些解决方案吗
感谢所有建议。这里有一个将进度条与中并发任务的进度相关联的示例
导入javafx.concurrent.Task;
任务=新任务(){
@重写公共无效调用(){
静态最终整数最大值=1000000;
对于(int i=1;i
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();