I am trying to use a simple program to read from a log file. The code used is as follows:
RandomAccessFile in = new RandomAccessFile("/home/hduser/Documents/Sample.txt", "r"); String line; while(true) { if((line = in.readLine()) != null) { System.out.println(line); } else { Thread.sleep(2000);
The code works well for new lines being added to the log file but it does not replicate the rollover process. i.e. when the content of the log file is cleared I expect the java console to continue reading text from the first line newly written to the log. Could that be possible? What changes need to be made to the existing code to achieve that?
Advertisement
Answer
I am sorry... My Bad.. I don't want it to go blank.. I just want the next new line written to the log to be read.
Since what you need is able to read from beginning when you file is cleared, you will need to monitor the length of file and reset the cursor pointer when length of file reduces. You can reset the cursor using seek(..)
method.
See code below –
RandomAccessFile in = new RandomAccessFile("/home/hduser/Documents/Sample.txt", "r"); String line; long length = 0;//used to check the file length while (true) { if(in.length()<length){//new condition to reset position if file length is reduced in.seek(0); } if ((line = in.readLine()) != null) { System.out.println(line); length = in.length(); } else { Thread.sleep(2000); } }