java - 监控文件更改

标签 java multithreading

我正在尝试监视文件内容并将任何新行添加到 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/

相关文章:

java - 获取发布到 JAXB Web 服务端点的 XML 字符串

c# - 取消长操作

java - Android中可以发生优先级倒置吗

java - Android:在Java/Kotlin中的ScrollView内部居中LinearLayout

java - 从 Iterator<T> 转换为 Iterator<U>,其中 T 是 U 的子类

java - 选择下拉菜单项时显示 `form`?

c# - 等待事件的正确方法

ios - 多个 NSManagedObjectContexts 问题

C#跨线程通信

java - 如何解释音频字节?