2017-03-01 28 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()並查找最終文件大小可能會非常棘手。這就是爲什麼我需要更具體的迴應。所有瀏覽器均實現此功能。 –