Skip to content

Instantly share code, notes, and snippets.

@debbabi
Created July 15, 2014 01:43
Show Gist options
  • Select an option

  • Save debbabi/8457f60a947f85ef6d43 to your computer and use it in GitHub Desktop.

Select an option

Save debbabi/8457f60a947f85ef6d43 to your computer and use it in GitHub Desktop.
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.*;
import java.io.*;
public class PHR {
public static void main(String[] args) throws IOException {
// monitor a single file
TimerTask task = new FileWatcher( new File("phrlist.txt") ) {
protected void onChange( File file ) throws IOException {
// here we code the action on a change
System.out.println( "File "+ file.getName() +" have change !" );
updated();
}
};
Timer timer = new Timer();
// repeat the check every second
timer.schedule( task , new Date(), 1000 );
}
private static void updated() throws IOException {
FileReader in = null;
FileWriter out = null;
BufferedReader input = null;
PrintWriter output = null;
try {
in = new FileReader("phrlist.txt");
input = new BufferedReader(in);
String s;
while ((s = input.readLine()) != null) {
//output.println(s);
System.out.println(">> " + s);
}
} finally {
if (input != null) {
input.close();
}
if (in != null) {
in.close();
}
}
}
public abstract static class FileWatcher extends TimerTask {
private long timeStamp;
private File file;
public FileWatcher( File file ) {
this.file = file;
this.timeStamp = file.lastModified();
}
public final void run() {
long timeStamp = file.lastModified();
if( this.timeStamp != timeStamp ) {
this.timeStamp = timeStamp;
try {
onChange(file);
} catch(Exception e) {
}
}
}
protected abstract void onChange( File file ) throws IOException ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment