/* TextFromWebServiceApp.java by Kari Laitinen http://www.naturalprogramming.com/ 2015-01-02 File created. Thir program demonstrates how to use Java FX classes to read a text file that is located on a server on the Internet. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import javafx.application.Application; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.stage.Stage; public class TextFromWebServiceApp extends Application { @Override public void start( Stage stage ) throws Exception { TextFromWebService text_service = new TextFromWebService() ; text_service.setUrl( "http://www.naturalprogramming.com/javabookprograms/javafilesextra/testfile.txt"); // Next, we specify what will be done after the Task, that is // specified inside the TextFromWebService class, is completed // successfully. text_service.setOnSucceeded( ( WorkerStateEvent event ) -> { System.out.println( event.getSource().getValue() ) ; } ) ; text_service.start() ; } public static void main( String[] not_in_use ) { launch() ; } private static class TextFromWebService extends Service { private StringProperty text_file_url = new SimpleStringProperty() ; public final void setUrl( String url_as_string ) { text_file_url.set( url_as_string ) ; } public final String getUrl() { return text_file_url.get() ; } public final StringProperty urlProperty() { return text_file_url ; } @Override protected Task createTask() { return new Task() { @Override protected String call() throws IOException, MalformedURLException { URL text_url = new URL( getUrl() ) ; BufferedReader buffered_reader = new BufferedReader( new InputStreamReader( text_url.openStream() ) ) ; StringBuilder all_text_lines = new StringBuilder() ; String text_line_from_web ; while ( ( text_line_from_web = buffered_reader.readLine() ) != null ) { all_text_lines.append( text_line_from_web + "\n" ) ; } buffered_reader.close() ; return all_text_lines.toString() ; } } ; } } } /* NOTES: The following pages might be useful to read: http://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm https://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Service.html http://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html // The following is another possible way to handle the OnSucceeded event: text_service.setOnSucceeded( new EventHandler() { @Override public void handle(WorkerStateEvent t) { System.out.println( t.getSource().getValue()); } } ) ; */