I'm trying to monitor the ".txt" file and read the data from it as it gets updated using the following method.
public void startFileMonitoring() throws InterruptedException {
log.info("Here");
String filePath = "file.txt";
File file = new File(filePath);
long lastModified = -1;
do {
try {
if (lastModified != file.lastModified()) {
RandomAccessFile in = new RandomAccessFile(filePath, "r");
String data = in.readLine();
log.info("Read Data : "+data+"\tdata length : "+data);
lastModified = file.lastModified();
in.close();
}
} catch (IOException e) {
log.error("Exception while reading file");
e.printStackTrace();
}
}while(true);
}
Interestingly, this method able to read the lastModified time correctly. So whenever we update anything in the file it tries to read the file. the issue is, it does not fetch any data (gives null).
What am i missing in this?
logs: file initially had string "abc". I changed it to "abcd".
2021-04-01 10:44:06.929 INFO 12760 --- [ task-1] com.service.FileReadingService : Read Data : abc
2021-04-01 10:44:11.626 INFO 12760 --- [ task-1] com.service.FileReadingService : Read Data : null
2021-04-01 10:44:18.402 INFO 12760 --- [ task-1] com.service.FileReadingService : Read Data : null
Pretty weird solution. While debugging tried printing object reference of RandomAccess in
and the code worked.
here is updated code :
public void startFileMonitoring(){
log.info("Here");
String filePath = "file.txt";
File file = new File(filePath);
long lastModified = -1;
do {
try {
if (lastModified != file.lastModified()) {
RandomAccessFile in = new RandomAccessFile(filePath, "r");
//in.seek(0L);
log.info("in : {}",in);
String data = in.readLine();
if(data == null) {
log.info("Data null here, in: {}",in);
}
if (data != null && applicationData.getSeenLinesFromFile().add(data)) {
applicationData.getLineDataToRead().add(data);
}
log.info("Read Data : " + data+"\tfile : "+file+"\tlasModified : "+lastModified);
lastModified = file.lastModified();
}
} catch (IOException e) {
log.error("Exception while reading file");
e.printStackTrace();
}
}while(true);
}