如何在java中将JFXProgressBar与我的链接绑定
我试图让java程序从我的服务器下载一个应用程序,通过以下代码获得下载链接:如何在java中将JFXProgressBar与我的链接绑定,java,progress-bar,progress,Java,Progress Bar,Progress,我试图让java程序从我的服务器下载一个应用程序,通过以下代码获得下载链接: private void downloadFile(String link) throws Exception { URL url = new URL(link); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); int max = conn.getContentLength(); pane.
private void downloadFile(String link) throws Exception {
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
int max = conn.getContentLength();
pane.setText(pane.getText()+"\n"+"Downloding files...\nUpdate Size : "+(max/1000000)+" Mb");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new
File("update.zip")));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
int in = 0;
while ((bytesRead = is.read(buffer)) != -1) {
in += bytesRead;
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
pane.setText(pane.getText()+"\nDownload Completed Successfully!");
它工作得很好。。。我确实搜索过如何将我的进度条绑定到这个下载链接,但我想不出来。。。。非常感谢您的帮助。创建一个任务,并以该任务的方法执行下载:
您甚至可以在任务更改时监视其消息:
downloader.messageProperty().addListener(
(o, oldMessage, newMessage) -> pane.appendText("\n" + newMessage));
如果下载失败,您可能想让用户知道。可以使用任务的属性执行此操作:
downloader.setOnFailed(e -> {
Exception exception = downloader.getException();
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
TextArea stackTraceField = new TextArea(stackTrace.toString());
stackTraceField.setEditable(false);
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.initOwner(pane.getScene().getWindow());
alert.setTitle("Download Failure");
alert.setHeaderText("Download Failed");
alert.setContextText(
"Failed to download " + link + ":\n\n" + exception);
alert.getDialogPane().setExpandableContent(stackTraceField);
alert.show();
});
任务实现Runnable,因此您可以通过将其传递给任何标准多线程类来启动它:
new Thread(downloader, "Downloading " + link).start();
或:
或:
谢谢你,伙计
downloader.setOnFailed(e -> {
Exception exception = downloader.getException();
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
TextArea stackTraceField = new TextArea(stackTrace.toString());
stackTraceField.setEditable(false);
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.initOwner(pane.getScene().getWindow());
alert.setTitle("Download Failure");
alert.setHeaderText("Download Failed");
alert.setContextText(
"Failed to download " + link + ":\n\n" + exception);
alert.getDialogPane().setExpandableContent(stackTraceField);
alert.show();
});
new Thread(downloader, "Downloading " + link).start();
CompletableFuture.runAsync(downloader);
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(downloader);