2017-05-16 39 views
1

guiと表示され、テキストファイルが表示されるアプリケーションを作成しています。テキストファイルの内容が変更されると、GUIへの変更が実行されます。しかし、私は常にguiを読んで、変更のためにテキストファイルをチェックする必要があります。私は単に制御を取るthread.sleep()を試して、ループ以外のコードは動作しません。周りを見回した後、私はスイングタイマーへの参照を見つけて、EDTではない新しいスレッドで実行しました。このものは私の上に失われ、私はそれを実装する方法を見つけることができません。どんな助けもありがとう。Javaのテキストファイルを監視する方法

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

}}

+0

[This](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html)は、開始するのに適しています。 –

+0

方法については、[この回答](https://stackoverflow.com/questions/16251273/can-i-watch-for-single-file-change-with-watchservice-not-the-whole-directory)も参照してください。ファイルを適切に監視して変更します。 – TeMPOraL

+0

特定の質問がありますか? – Michael

答えて

0

これは、ファイル監視のためだけの簡単なコードで、それはあなたを助けることができると思います。

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(); 
+0

JavaにはAPIがあります。独自のAPIを使用するよりもAPIを使用するほうがよいでしょう。https://docs.oracle.com/javase/tutorial/essential/io/notification.html – Michael

+0

はい、わかります。初心者のプログラマーのための簡単な例です。 –

関連する問題