2011-08-01 76 views
0

我试图监视文件内容并向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(); 
     } 

    } 

} 


} 
+0

您可以发布您的代码吗? – Maverik

+0

什么问题?代码在哪里? –

+3

[unix/linux的Java IO实现“tail -f”]的可能的重复(http://stackoverflow.com/questions/557844/java-io-implementation-of-unix-linux-tail-f) – NPE

回答

1

wait方法是不是你想要的这里。改为尝试Thread.sleep

+0

我改变了它。这是相当老的代码,在我的实验之前 – jacbar