1

I am making an application that will display a gui and read a text file. When the contents of the text file changes it will execute changes to the gui. However i need the gui to constantly be reading and checking the textfile for changes. I have tried thread.sleep() which just takes control and no code works other than the loop. After looking around i found reference to swing timers and running in new threads that weren't the EDT. This stuff is lost on me and I can find no way to implement it. Any help would be appreciated.

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

} }

NEKIBUR RAHMAN
  • 204
  • 3
  • 15
Kyle
  • 31
  • 7
  • [This](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) should be a good place to start. – Andrew S May 16 '17 at 20:17
  • See also [this answer](https://stackoverflow.com/questions/16251273/can-i-watch-for-single-file-change-with-watchservice-not-the-whole-directory) for a way to properly watch a file for modifications. – TeMPOraL May 16 '17 at 20:26
  • Do you have a specific question? – Michael May 16 '17 at 21:20

1 Answers1

0

This is just a simple code for file monitoring, hope it can help you.

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();
NEKIBUR RAHMAN
  • 204
  • 3
  • 15