2017-03-01 72 views
0

我写了一段代码,用于从互联网下载文件(在后台服务中),并在弹出的阶段显示下载进度。代码编译成功,没有运行时错误。然而,没有下载发生,并且进度指示器保持不确定。进度指示器保持不确定状态,没有下载

该代码是为了说明我的观点而定制的。请看看它,让我明白我出错的地方。

谢谢!

public class ExampleService extends Application { 
URL url;  
Stage stage; 

public void start(Stage stage) 
{ 
    this.stage = stage; 
    stage.setTitle("Hello World!"); 
    stage.setScene(new Scene(new StackPane(addButton()), 400, 200)); 
    stage.show(); 
} 

private Button addButton() 
{ 
    Button downloadButton = new Button("Download"); 
    downloadButton.setOnAction(new EventHandler<ActionEvent>() 
    { 
     public void handle(ActionEvent e) 
     { 
      FileChooser fileSaver = new FileChooser(); 
      fileSaver.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF", "pdf"));     

      File file = fileSaver.showSaveDialog(stage); 

      getDownloadService(file).start();    
     } 
    });   
    return downloadButton; 
} 

private Service getDownloadService(File file) 
{ 
    Service downloadService = new Service() 
    { 
     protected Task createTask() 
     { 
      return doDownload(file); 
     } 
    }; 

    return downloadService; 
} 

private Task doDownload(File file) 
{ 
    Task downloadTask = new Task<Void>() 
    { 
     protected Void call() throws Exception 
     { 
      url = new URL("http://www.daoudisamir.com/references/vs_ebooks/html5_css3.pdf"); 

      // I have used this url for this context only 
      org.apache.commons.io.FileUtils.copyURLToFile(url, file); 

      return null; 
     } 
    }; 
    showPopup(downloadTask); 
    return downloadTask; 
} 

Popup showPopup(Task downloadTask) 
{ 
    ProgressIndicator progressIndicator = new ProgressIndicator(); 
    progressIndicator.progressProperty().bind(downloadTask.progressProperty()); 

    Popup progressPop = new Popup(); 
    progressPop.getContent().add(progressIndicator); 
    progressPop.show(stage); 

    return progressPop; 

    // I have left out function to remove popup for simplicity 
} 
public static void main(String[] args) 
{ 
    launch(args); 
}} 
+0

如果有例外,你不会知道它。注册一个'onFailed'处理程序,任务:'downloadTask.setOnFailed(e - > downloadTask.getException()。printStackTrace());'。如果你想改变进度,你需要调用['updateProgress(...)'](http://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html#updateProgress -long-long-)来自你的'call()'方法。 –

回答

1

行:

org.apache.commons.io.FileUtils.copyURLToFile(url, file);

...不会向您提供关于您的下载进度的任何信息(没有回调或者其进展的任何其他指示)。它只是下载一些东西而不给你反馈。

你将不得不使用别的东西来反馈你的进度。

看看这个问题的答案与反馈解决方案(它是摇摆的,但你应该能够适应他们的JavaFX):Java getting download progress

+0

我看了你的链接。我将不得不弄清楚如何使代码适应JavaFX。代码使用Java.io,而我想使用org.apache.commons.io。这更简单的使用。 –

0

您的ProgressIndicator的进步属性为Task“绑定因此后者的变化将反映在前者中。然而你从来没有实际更新你的Task的进展

如果您希望进度指示器显示某些内容,您必须在任务的正文(或其他地方)中调用updateProgress(workDone, max)。如果你使用的下载逻辑不给你任何进度回调,那可能会很棘手。 (你也许可以生成一个线程来重复检查文件系统上的文件大小,并将其用作当前的workDone;但是你需要知道该文件的最终/完整大小是为了转向这变成了一个百分比,这可能会也可能不容易。)

+0

我明白,使用updateProgress()并查找最终文件大小可能会非常棘手。这就是为什么我需要更具体的回应。所有浏览器均实现此功能。 –