Thursday, April 2, 2009

Continuous File Reading In Java

So i recently worked on a project and a requirement came up to be able to read a text file which was been written to at regular intervals to be read continuously. While searching on the web i did not find much help with this regard, hence i started my journey on finding a solution to this on my own and was in the end successful though i might have wasted a wee bit of my development time. But it was overall a really valuable learning experience and i thought of sharing it with you all so that if ever you do get the need for continuous file reading in java, you can find it right here.

private static void continuousFileReader(String fileName) {

String appFileName = fileName+"/fileName.txt";
File file = new File(appFileName);
if(!(file.exists())){
System.out.println("Relevant File Does Not Exist At " +fileName+" Hence Exiting System");
System.exit(1);
}

long lengthBefore = 0;
long length = 0;



while(true){
RandomAccessFile reader = null;
try {
if ((length = file.length()) > lengthBefore) {

try {

reader = new RandomAccessFile(file,"r");
reader.seek(lengthBefore);
lengthBefore = length;
String line = null;
while (!((line = reader.readLine()) == null)) {
// do whatever with contents
}

} catch (FileNotFoundException ex) {
//handle exception
}

catch (IOException ex) {
//handle exception
}

}

Thread.sleep(10000);
} catch (InterruptedException ex) {
try {
if(reader!=null){
reader.close();
}
} catch (IOException ex1) {
//handle exception
}
}
}


}

And one more thing to note is to remember to block the main thread using a while(true) condition because otherwise the continuous file reading will end if the main thread halts ;) .

This is my very first post and my first time blogging so if you guys see any mistakes, constructive criticisms or what ever you might call it please feel free to share your thoughts :D.

Until then, its Adieu from my side.