我写了一段代码来比较时间戳以检查文件修改
这是代码
private long timeStamp;
private File file;
private boolean isFileUpdated(File file)
{
this.file = file;
this.timeStamp = file.lastModified();
if (this.timeStamp != timeStamp)
{
this.timeStamp = timeStamp;
// Yes, file is updated
return true;
}
// No, file is not updated
return false;
}
public static void main(String[] args)
{
Test test=new Test();
File testFile=new File("D:/Test/Test.txt");
boolean result=test.isFileUpdated(testFile);
System.out.println("the result is " + result);
}
此代码的问题是它不保留任何时间戳记录。那么我是否需要将时间戳放在txt文件中,以便从txt文件中读取并比较当前lastmodifieddate以及是否有更改意味着文件已被修改?
答案 0 :(得分:1)
这将为您写下您的历史记录:
PrintWriter writer = new PrintWriter(FileWriter(new File("log.log"), true));
//true for append mode
writer.println(file.lastModified());
writer.close();
您可以使用像这样的扫描仪阅读它
Scanner s = new Scanner(new File("log.log"));
String line = null;
while (s.hasNextLine()) {
line = s.nextLine();
}
s.close();
//line is the last line read