我正在尝试监视文件内容并将任何新行添加到 JTextArea。我创建了监视文件的线程,但是当扫描仪对象到达文件末尾时,它停止工作。我尝试了非常简单的方法,它创建新的 Scanner 对象并从头开始读取文件,但这不是一个好的解决方案。 这是停止并且不执行任何操作的版本:
public class TextAreaThread implements Runnable {
JTextArea text = null;
File file = null;
Scanner read = null;
public TextAreaThread(JTextArea text, File file) {
this.text = text;
this.file = file;
try{
read = new Scanner(file);
}catch(FileNotFoundException e){
JOptionPane.showMessageDialog(null,"Wrong file or file doesn't exist","Error",JOptionPane.ERROR_MESSAGE);
}
}
public void run() {
while(true){
while(read.hasNext())
text.append(read.nextLine()+"\n");
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
最佳答案
wait
方法不是您想要的。尝试使用 Thread.sleep 来代替。
关于java - 监控文件更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6898533/