0

I'm trying to write a java program that reacts if a new entry occures in the file C:/xampp/apache/logs/access.log in order to recognize a new request to my Apache Server.

I used the following code:

    public static void monitor() throws IOException {
    WatchService watcher = FileSystems.getDefault().newWatchService();


    File file = new File("C:/xampp/apache/logs/");
    Path dir = file.toPath();
    dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);

    for (;;) {

        // wait for key to be signaled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();


            // get file name
            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path fileName = ev.context();

            System.out.println(kind.name() + ": " + fileName);

            if (kind == OVERFLOW) {
                continue;
            } else if (kind == ENTRY_CREATE) {

                System.out.println("entry created occured");
                // process create event

            } else if (kind == ENTRY_DELETE) {

                // process delete event

            } else if (kind == ENTRY_MODIFY && fileName.toString().equals("access.log")) {
                System.out.println("entry modified occured");
                // process modify event

            }
        }

        // Reset the key -- this step is critical if you want to
        // receive further watch events. If the key is no longer valid,
        // the directory is inaccessible so exit the loop.
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}

But it does not recognize the change in access.log until I manually open the file. Is there something wrong with my code?

Vik Toria
  • 29
  • 1
  • 7

1 Answers1

0

There are differents options.

There are two questions that can be kind of similiar, the only difference is that they want to check a whole direcotry instead of just a file, but you could adapt the code to detect if the modified file is the one that you want.

Watching a Directory for Changes in Java

Java detect changes in filesystem

For a specific solution I've found

http://www.rgagnon.com/javadetails/java-0490.html

This code launches a thread that checks the lastModified value of the file, if it's different from the previous one, it means that the file has been modified. I don't know if it's very efficient, check them out.

Peter Rubi
  • 119
  • 1
  • 12