0

I want to read from a text file such that whenever i add a line to my text file and save it, the java program should read that particular line and print it. So far i have something like this:

FileReader fileReader = new FileReader(filename);
BufferedReader bufReader = new BufferedReader(fileReader);

while (true){

  if (bufReader.ready()){
       String line = bufReader.readLine();
       System.out.println(line);
       continue;
  }
  else {
       Thread.sleep(5000);
       continue;
  }
}

This code doesn't print the new lines once the program is running and i update the text file and save. Is there a way how i could achieve this?

stud91
  • 1,854
  • 6
  • 31
  • 56
  • because of this `String line = bufReader.readLine();` every time it prints same line. – SatyaTNV Jul 29 '15 at 17:07
  • 1
    Another note, your `continue;` lines are redundant. The while loop will continue regardless. – CubeJockey Jul 29 '15 at 17:08
  • 2
    possible duplicate of [Java IO implementation of unix/linux "tail -f"](http://stackoverflow.com/questions/557844/java-io-implementation-of-unix-linux-tail-f) – fgb Jul 29 '15 at 17:09

2 Answers2

0

I guess you can get a idea from this code:

BufferedReader br = new BufferedReader(fileReader);
String line;
while (true) {
    line = reader.readLine();
    if (line == null) {

        Thread.sleep(5000);//waiting till the new content
    }
    else {
       // Read the line
    }
}
XOR-Manik
  • 493
  • 1
  • 4
  • 19
0

Use apache-commons-io instead of rolling your own implementation. It has an implementation of "tail -f" functionality that you are trying to achieve.

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/Tailer.html

kjp
  • 3,086
  • 22
  • 30