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) {
try {
} catch (InterruptedException x) {
return isException;


techboard said...

I believe its much easier in Java 7 using NIO (

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, 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 .

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.

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.