Monday, April 25, 2011

How to write Java code to listen runtime changes in text file

I had a requirement to write a java code to listen continues changing text file.i have used following code to do that.

public void listenServer() throws IOException {
Reader fileReader = new FileReader("/home/chamara/server.log");
BufferedReader input = new BufferedReader(fileReader);
String line = null;
while (true) {
if ((line = input.readLine()) != null) {
System.out.println(line);
continue;
}
try {
Thread.sleep(1000L);
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
break;
}
}
input.close();
return isException;
}

7 comments:

techboard said...

I believe its much easier in Java 7 using NIO (http://download.oracle.com/javase/tutorial/essential/io/notification.html)

Oliver said...

Even prior to Java 7, I would consider to check the file's modification date before going to read the contents.

In conjuction with http://code.google.com/p/google-diff-match-patch/, one could then easily find out "what" was actually changed.

JavaAmtho said...

@techboard, It would implement easily using channel of new java nio concept.

niedbalski said...

Why not just use some notify syscall? ( Inotify, Kqueue ) to monitor for changes ?

Javin Paul said...

When I saw title of your blog I got surprised by name "Chamara Silva" I thought its cricket from SriLanka :)
anyway nice post .

Javin
How Garbage collection works in Java

Anonymous said...

Good code. However, I agree with others. Also, there is a Java project called JNotify that can be useful here. http://jnotify.sourceforge.net/

---
Josef B.

Loak said...

There is also a FileListener in JNA packages that uses native function. In my project we had many time similar requirements, Java7 was not available and we couldn't use JNA. We wrote our own FileListener, using file last modification time was the best solution we found.