1

Possible Duplicate:
How do I use Java to read from a file that is actively being written?

I have a program(Trap reciever) which appends a string to the end of a file. This program basically logs everything it does.

I want my program to read of that log file. What problems can i face doing this and what is the most efficient way to do this. Reading a file while another process updates it.

Community
  • 1
  • 1
Mustafa
  • 1,738
  • 2
  • 24
  • 34
  • 1
    -1 for duplicacy : You can find your answer here : http://stackoverflow.com/questions/4149/how-do-i-use-java-to-read-from-a-file-that-is-actively-being-written please check if the question already exists or not before posting it. – Mukul Goel Oct 03 '12 at 08:14

1 Answers1

2

Is suppose that this logger, as most loggers, don't just append any kind of strings but whole lines.

You can simply use a bufferedReader and wait if you have nothing :

BufferedReader br = new BufferedReader(new FileReader("path"));
String line;
while (true) {
    line = br.readLine();
    if (line != null) {
        // do something
    } else {
        Thread.sleep(DELAY);   // DELAY could be 100 (ms) for example     
    }
}

Of course you'd have to do this in a separate thread if your application has other tasks to accomplish.

If you want to avoid pulling, in case of very rare loggings, you might use a watch service but I never tried it on a simple file and I'm not sure it would be always reliable.

Tom-Oliver Heidel
  • 1,011
  • 9
  • 25
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thank you very much Dystroy.....I did some research on google and came up something called mutex which is like file lock i believe. Will this approach bypass that problem? – Mustafa Oct 03 '12 at 08:16
  • Mutex are a different thing : they're use to synchronize different threads. I don't think a mutex could be useful here. – Denys Séguret Oct 03 '12 at 08:19
  • I see. Thank you. This code will be used for a server which will run 24/7 most likely. Hopefully this code does not crash haha. I wil let you know how it goes. Thank you once more. – Mustafa Oct 03 '12 at 08:21
  • Don't forget to catch IO exceptions and, if needed, to reopen the reader. Another detail : most 24/7 loggers change files every day (or when too big) so you may have to watch a directory and not just a file. – Denys Séguret Oct 03 '12 at 08:23
  • Appreciate it. I will write the best est code as i can. – Mustafa Oct 03 '12 at 08:25