在javafx中动态读取文本文件

时间:2015-03-08 05:20:19

标签: javafx

我需要读取aad文本文件并在文本区域中显示内容,但问题是我的文本文件每秒都在更新。是可以动态显示文本区域中的文本文件的内容,即,每隔一个新数据被添加到文本文件中,我还需要显示新数据

这是我在控制器中的代码

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);
    }
}

1 个答案:

答案 0 :(得分:1)

我现在想测试手表功能一段时间了,所以我抓住了你的问题并给你一个榜样。请根据您的需要调整watchPath。该文件最初不必存在。一旦你创建它就会被发现。

/**
 * 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);
    }

}