我正在制作一个应用程序,它将显示gui并读取文本文件。当文本文件的内容发生更改时,它将执行对 gui 的更改。但是,我需要gui不断地读取和检查文本文件是否有更改。我尝试过 thread.sleep() ,它只是控制,除了循环之外没有代码工作。环顾四周后,我发现了关于 Swing 计时器的引用,并在不是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();
关于java - java中如何监控文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44010692/