您可以将 RandomAccessFile 类用于您的代码。
我的代码:
import java.io.*; //Importing RandomAccessFile Class
import java.util.*; // Thread.sleep(milliseconds)
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
/*Just To add functionality I have also specified the time at which the file is modified*/
System.out.println("Input File Path : ");
String file_path = scan.nextLine();
RandomAccessFile f = new RandomAccessFile(file_path,"r");
int character;
String Intitalval="";
while ((character = f.read()) != -1) {
Intitalval+=(char)character;
}
f.seek(0);
boolean nochange = true;
while (nochange) {
String ToCompare="";
while ((character = f.read()) != -1) {
ToCompare+=(char)character;
}
if (!ToCompare.equals(Intitalval)) {
nochange = false;
System.out.println("The file has been modified at " + java.time.LocalTime.now());
}
Thread.sleep(1);
f.seek(0);
}
f.close();
}
}
正如您所说,您想要延迟 1 毫秒,我使用了 javaThread.sleep(int milliseconds)方法。
该程序还将显示文件被修改的时间(不准确(+- 毫秒))。
输出 :
