updateProgress()方法不起作用

时间:2017-03-02 16:38:28

标签: java javafx

我已经在此论坛上发布了以下采用的代码版本。该代码应该从URL下载给定文件并显示下载进度。它能够检索文件大小和打印"下载成功"。它也按照成功的指示行事。但是,既没有在选定位置下载也没有进度指示器显示任何进度。似乎updateProgress()方法什么都不做。它是某种错误,我的逻辑缺陷,还是平台不兼容?我在Windows 8.1 64位上的NetBeans 8.1上使用JDK 1.8.0_101。

这是代码。

public class FileLength extends Application {
BorderPane root;    
String url;
File file;
ProgressIndicator pi;
Stage stage;
public void start(Stage primaryStage) 
{
    stage = primaryStage;
    DownloadTask task = new DownloadTask();
    Button btn = new Button();
    btn.setText("Get File");
    btn.setOnAction(new EventHandler<ActionEvent>()
    {

        public void handle(ActionEvent event)
        {
            FileChooser fileSaver = new FileChooser();
            fileSaver.getExtensionFilters().add(new FileChooser.ExtensionFilter("ZIP", ".zip"));                

            file = fileSaver.showSaveDialog(stage);
            new Thread(task).start();
        }
    });

    root = new BorderPane();        
    root.setBottom(btn);

    pi = new ProgressIndicator();
    pi.progressProperty().bind(task.progressProperty());
    /* why this is not binding? */
    root.setTop(pi);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Download progress");
    primaryStage.setScene(scene);
    primaryStage.show();
}

private  class DownloadTask extends Task<Void>
{
    protected Void call()
    {
        try
        {
            URL url = new URL("http://downloads.sourceforge.net/project/bitcoin/Bitcoin/blockchain/bitcoin_blockchain_170000.zip");
            /* url is for example only */

            HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
            long completeFileSize = httpConnection.getContentLength();
            System.out.println("File size:" + completeFileSize );

            InputStream is = httpConnection.getInputStream();
            OutputStream os = new FileOutputStream(file);

            long downloadedFileSize = 0L;
            byte[] buf = new byte[1024];
            int n = 0;

            while ((n = is.read(buf, 0, 1024)) >= 0) 
            {                   
                downloadedFileSize += n;
                updateProgress(downloadedFileSize, completeFileSize);
                /* why this is not updating progress?*/
                os.write(buf, 0, n);                   
            }
            is.close();
            os.close();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }            

        return null;
    }
    protected void succeeded()
    {
        // this executes
        System.out.println("Download succeeded");
        root.getChildren().remove(pi);
    }
    protected void failed()
    {
        System.out.println("Download failed");
    }  
}
public static void main(String[] args)
{
    launch(args);
} }

0 个答案:

没有答案