如何使用Java检测Windows文本文件中是否有最近的更改 [英] How to detect if there is recent change in windows text file using Java
本文介绍了如何使用Java检测Windows文本文件中是否有最近的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我正在用 java 编写一个小应用程序,它读取文本文件并解析内容.我的问题是我的程序会继续读取文件,因为它在一个循环内.我的解决方案是实现类似于我通常在 linux 中做的事情(见下文)
Hi guys I am writing a small application in java where it reads a text file and parses the contents. My problem is my program will keep on reading the file because its inside a loop. My solution was to implement similar to what I usually do in linux like (see below)
ls -l -ctime
or
ls -l -atime
它检测文件上次访问或写入时间的位置如果您的解决方案可以用 java 或某些 Windows 命令完成,请告诉我.谢谢
where it detects when the files was last accessed or written If you solution can be done in java or some windows command can you please let me know. Thanks
非常感谢您的帮助
韦斯顿解决方案
public static long checkLastFileModification() throws InterruptedException{
File file = new File(fileName);
long lastProcessed = -1;
while (true){
long lastModified = file.lastModified();
if (lastProcessed != lastModified){
lastProcessed = lastModified;
System.out.println("Last accessed : " + lastModified);
//read the file in reverse order
}
else{
System.out.println("No file access.... sleeping for 5 secs ");
Thread.sleep(5000);
}
}
}
推荐答案
您可以查看 文件的最后修改时间:
new File(fileName).lastModified()
在你的循环中你可以看到它是否不同:
In your loop you can see if it is different:
long lastProcessed = -1;
File file = new File(fileName);
while(true) {
long lastModified = file.lastModified();
if (lastProcessed != lastModified) {
lastProcessed = lastModified;
process(file);
}
else {
//some delay or sleep, else you're thrashing the thread and file
}
}
这篇关于如何使用Java检测Windows文本文件中是否有最近的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文