user3809411
user3809411

Reputation: 346

read a text file dynamically in javafx

I need to read aad text file and show the content in text area but the problem is that my text file is updating with every second . IS that possible to show the content of text file in text area dynamically i.e., with every second new data is added into text file and i need to show the new data also

this is my code in the controller

public void initialize(URL url, ResourceBundle rb) {

    try {
        Scanner s = new Scanner(new File("E:\\work\\programming\\NetBeansProjects\\FinalProject\\src\\logs\\diskCheck.txt")).useDelimiter("\\s+");
        while (s.hasNext()) {
            if (s.hasNextInt()) { // check if next token is an int
                diskchecktextarea.appendText(s.nextInt() + " "); // display the found integer
            } else {
               diskchecktextarea.appendText(s.next() + " "); // else read the next token
            }
        }
    } catch (FileNotFoundException ex) {
        System.err.println(ex);
    }
}

Upvotes: 0

Views: 1885

Answers (1)

Roland
Roland

Reputation: 18425

I've wanted to test the watch feature for a while now, so I took the chance with your question and made you an example. Please adapt the watchPath to your needs. The file doesn't have to exist initially. It'll be found once you create it.

/**
 * Documentation: https://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes
 */
public class WatchFileChanges extends Application {

    Path watchPath = Paths.get("c:/temp/watch.txt");

    TextArea textArea;

    @Override
    public void start(Stage primaryStage) throws IOException {

        BorderPane root = new BorderPane();

        textArea = new TextArea();
        root.setCenter(textArea);

        Scene scene = new Scene(root, 800, 600);

        primaryStage.setScene(scene);
        primaryStage.show();

        // load file initally
        if (Files.exists(watchPath)) {
            loadFile();
        }

        // watch file
        WatchThread watchThread = new WatchThread(watchPath);
        watchThread.setDaemon( true);
        watchThread.start();

    }

    private void loadFile() {

        try {

            String stringFromFile = Files.lines(watchPath).collect(Collectors.joining("\n"));
            textArea.setText(stringFromFile);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private class WatchThread extends Thread {

        Path watchPath;

        public WatchThread(Path watchPath) {
            this.watchPath = watchPath;
        }

        public void run() {

            try {

                WatchService watcher = FileSystems.getDefault().newWatchService();
                WatchKey key = watchPath.getParent().register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);

                while (true) {

                    // wait for key to be signaled
                    try {
                        key = watcher.take();
                    } catch (InterruptedException x) {
                        return;
                    }

                    for (WatchEvent<?> event : key.pollEvents()) {

                        WatchEvent.Kind<?> kind = event.kind();

                        if (kind == StandardWatchEventKinds.OVERFLOW) {
                            continue;
                        }

                        WatchEvent<Path> ev = (WatchEvent<Path>) event;

                        Path path = ev.context();

                        if (!path.getFileName().equals(watchPath.getFileName())) {
                            continue;
                        }

                        // process file
                        Platform.runLater(() -> {
                            loadFile();
                        });

                    }

                    boolean valid = key.reset();
                    if (!valid) {
                        break;
                    }

                }
            } catch (IOException x) {
                System.err.println(x);
            }
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Upvotes: 1

Related Questions