Reputation: 5464
What is the least-overhead way in Java 8+ to poll/read a small plain ASCII file to check if it changed?
I have a device that creates a fake filesystem (ev3dev) that provides small read-only files with status updates. (eg. a lego motor's position in a position
file with a single Int, or the motor's status in a status
file with a single String, both served up as a plain ASCII file)
Things that didn't work:
mark()
and reset()
to read the file over and over without creating a new Reader doesn't seem to work on a BufferedReader, are there ways to make it work?I think I have to poll: quickly read the file over and over (and over. and over!)
Upvotes: 1
Views: 560
Reputation: 114
You can use the RandomAccessFile class for your code.
My code :
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();
}
}
As you said you want a delay of 1 millisecond I have used java Thread.sleep(int milliseconds)
method.
The program will also display the time at which the file is modified (not accurate (+- milliseconds)).
Output :
Upvotes: 1