【问题标题】:How to monitor a text file in java如何在java中监控文本文件
【发布时间】:2017-05-16 20:08:28
【问题描述】:

我正在制作一个显示 gui 并读取文本文件的应用程序。当文本文件的内容发生变化时,它将执行对 gui 的更改。但是我需要 gui 不断地阅读和检查文本文件的变化。我已经尝试过 thread.sleep() ,它只是控制并且除了循环之外没有代码工作。环顾四周后,我发现了对摆动计时器的引用,并在不是 EDT 的新线程中运行。我失去了这些东西,我找不到实现它的方法。任何帮助将不胜感激。

       public void run() {
         initComponents();
    while(true){System.out.println("ok");
        try {

             try {
        File myFile = new File("C:\\Users\\kyleg\\OneDrive\\Documents\\123.txt");
        System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());

        Scanner input = new Scanner(myFile);
        String in = "";
        in = input.nextLine();
        System.out.println(in);
       switch(in){
        case("1"):
            break;
            case("2"):
            break;
            case("3"):
            break;
       }
    } catch (IOException ex) {
        Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
    }

            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }

} }

【问题讨论】:

  • This 应该是一个不错的起点。
  • 另请参阅this answer,了解正确查看文件以进行修改的方法。
  • 您有什么具体问题吗?

标签: java multithreading user-interface


【解决方案1】:

这只是一个简单的文件监控代码,希望对你有所帮助。

File f = new File("Path_to_the_file");
    new Thread(new Runnable() {
        @Override
        public void run() {
            long l = f.lastModified();
            String s = "";
            while (true) {

                if (f.lastModified() == l) {
                    System.out.print();
                } else {
                    try {
                        Scanner sc = new Scanner(f);
                        s = "";
                        while (sc.hasNext()) {
                            s += sc.nextLine();
                            s += "\n";
                            jTextArea1.setText(s);
                        }
                        System.out.println(false);
                        l = f.lastModified();
                        sc.close();
                    } catch (FileNotFoundException ex) {
                        System.out.println(ex);
                    }
                }

            }
        }

    }).start();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多