-4

I would like to create a java program which would poll a log file infinitely. Whenever there is some entry into that logfile, i would like to read the latest contents into the file just written.

can anyone please let me know the efficient method to do this? as this should run 24/7 getting cpu spikes is not desirable.

i did my basic research and found the following but didnt help much: https://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes

  • 1
    Please read [ask]. This kind of question is not acceptable as it is too broad and also shows no attempt (**code**) by you. – Idos May 19 '16 at 12:01
  • 3
    Sounds like you're looking for [how to implement `tail -f` in Java](http://stackoverflow.com/questions/557844/java-io-implementation-of-unix-linux-tail-f) – Andy Turner May 19 '16 at 12:22

1 Answers1

1

A very simple and efficient way to go about this is to use a WatchService. Here is a code example, which raises events when the file has been CREATED, MODIFIED, DELETED.

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKind;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

public static void main(String[] args) {

    //define a folder root
    Path myDir = Paths.get("D:/data");       

    try {
       WatchService watcher = myDir.getFileSystem().newWatchService();
       myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE, 
       StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);

       WatchKey watckKey = watcher.take();

       List<WatchEvent<?>> events = watckKey.pollEvents();
       for (WatchEvent event : events) {
            if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
                System.out.println("Created: " + event.context().toString());
            }
            if (event.kind() == StandardWatchEventKind.ENTRY_DELETE) {
                System.out.println("Delete: " + event.context().toString());
            }
            if (event.kind() == StandardWatchEventKind.ENTRY_MODIFY) {
                System.out.println("Modify: " + event.context().toString());
            }
        }

    } catch (Exception e) {
        System.out.println("Error: " + e.toString());
    }
}
ctotolin
  • 183
  • 5
  • Thank you @totolin for your answer but this does not extract the latest changes made in file. I am basically trying to read the latest content in the file once appended. – Shreyas Sarvothama May 19 '16 at 12:41