如何将 JFX ProgressBar 与我在 java 中的 link 绑定

how to bind JFX ProgressBar with my link in java

我正在尝试让 java 程序从我的服务器下载应用程序,方法是使用以下代码从服务器下载 link :

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

它工作正常...我确实搜索了如何将我的进度条绑定到此下载 link 但我无法弄清楚....我将不胜感激任何帮助。

创建一个Task and perform your download in that Task’s call方法:

String link = /* ... */;

File downloadsDir = new File(System.getProperty("user.home"), "Downloads");
downloadsDir.mkdir();

File file = File(downloadsDir, "update.zip");

Task<Void> downloader = new Task<Void>() {
    @Override
    public Void call()
    throws IOException {
        URL url = new URL(link);
        URLConnection conn = url.openConnection();

        long max = conn.getContentLengthLong();

        updateMessage(
            "Downloading files...\nUpdate Size : " + (max/1000000) + " MB");

        try (InputStream is = conn.getInputStream();
             BufferedOutputStream fOut = new BufferedOutputStream(
                new FileOutputStream(file))) {

            byte[] buffer = new byte[32 * 1024];

            int bytesRead = 0;
            long in = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                in += bytesRead;
                fOut.write(buffer, 0, bytesRead);
                updateProgress(in, max);
            }
        }

        updateMessage("Download Completed Successfully!");

        return null;
    }
};

注意继承方法的使用updateProgress and updateMessage

然后您可以简单地将 ProgressBar 的属性绑定到您的任务的属性。

progressBar.progressProperty().bind(downloader.progressProperty());

您甚至可以在任务消息发生变化时监视它:

downloader.messageProperty().addListener(
    (o, oldMessage, newMessage) -> pane.appendText("\n" + newMessage));

如果下载失败,您可能想让用户知道。您可以使用任务的 onFailed 属性:

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,因此您可以通过将其传递给任何标准多线程来启动它 class:

new Thread(downloader, "Downloading " + link).start();

或:

CompletableFuture.runAsync(downloader);

或:

ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(downloader);