下面是一个测试Timertask类,我一直在试验。基本上,timertask在一个文件改变时观察,然后执行一些方法。我希望打印给用户的消息,例如,只要timertask正在运行,就等待“等待文件更改发生”。命令应该输入哪里?以下是我的代码。Java - 只要TimerTask正在运行,打印消息
谢谢!
public class FileWatcherTest {
static int count = 3;
static int i = 0;
public static void main(String[] args) {
final Timer timer = new Timer();
System.out.println("Starting Timer " + timer.toString());
TimerTask task = new FileWatcher(new File("c:/temp/text.txt")) {
protected void onChange(File file) {
i++;
System.out.println("Executing iteration " + i);
System.out.println("File " + file.getName() +
" have change !");
// code to cancel timer
if (i >= count) {
System.out.println("Finished Iterations");
System.out.println("Stopping Timer");
timer.cancel();
System.out.println("Stopped Timer");
} else {
}
}
};
// repeat the check every second
timer.schedule(task, new Date(), 1000);
}
}
什么是'TimerTask任务=新的FileWatcher'应该是什么意思? – njzk2
它是一个扩展TimerTask的抽象类。基本上监视修改日期的文件。 – spry
你什么时候打电话给'onChange'? – njzk2