[英]How to monitor a text file in java
我正在制作一個顯示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);
}
}}
這只是一個簡單的文件監控代碼,希望它可以幫到你。
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.