minte9
LearnRemember



Watch Service

The java.nio.file package provides a file change notification API.
 
/**
 * Create a new WatchService
 * register the path instance for the folder and required type events ...
 * and then implement an infinite loop to wait for incomming events
 */

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchService;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;

public class App {

    public static void main(String[] args) {

        System.out.println("Events: ");

        try {
            WatchService watchService = 
                FileSystems.getDefault().newWatchService();
            Path path = Paths.get("/var/www/java/");
            path.register(watchService, ENTRY_MODIFY, ENTRY_DELETE);

            WatchKey watchKey = watchService.take();
            while (true) {
                
                for (WatchEvent<?> event : watchKey.pollEvents()) {
                    System.out.println(
                        "Event kind: " + event.kind() + " - " +
                        "File: " + event.context()
                    );
                }
                boolean valid = watchKey.reset();
                if (!valid) {
                    break;
                }
            }
            
            watchService.close();

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}
We can use threads to watch multiple directories.
 
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;

public class App {

    public static void main(String[] args) {

        System.out.println("WatchTread is runnnig:");

        new Thread(new Watch("/var/www/java/")).start();
        new Thread(new Watch("/var/www/php/")).start();
    }
}

class Watch implements Runnable {

    WatchService watchService;

    public Watch(String dir) {

        try {
            Path path = Paths.get(dir);
            watchService = FileSystems.getDefault().newWatchService();
            path.register(watchService, ENTRY_CREATE, ENTRY_MODIFY);

            Thread.sleep(1000); // help threads take turns
            
        } catch(IOException e) { e.printStackTrace(); 
        } catch(InterruptedException e) { e.printStackTrace(); 
        }
    }

    @Override
    public void run() {

        while(true) {
            try {
                WatchKey watchKey = watchService.take();
                for(WatchEvent<?> event : watchKey.pollEvents()) {
                    System.out.println(
                        "Event kind: " + event.kind() + " - " +
                        "File: " + event.context()
                    );
                }
                watchKey.reset();
            } catch (InterruptedException e) { 
                e.printStackTrace(); 
            }
        }
    }
}
Check directory for daily changes.
 
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class App {

    public static void main(String[] args) {

        String now = new SimpleDateFormat("HHmm").format(new Date());

        if (Integer.parseInt(now) >= 2130) { // 21:30
            new Thread(new Watch("/var/www/java/")).start();
        }

        if (Integer.parseInt(now) >= 2140) { // 21:40
            new Thread(new Watch("/var/www/php/")).start();
        }
    }
}

class Watch implements Runnable {

    String dir;

    public Watch(String dir) {
        this.dir = dir;
    }

    @Override
    public void run() {

        while(true) {

            System.out.println(new Date() + " watch " + dir);

            File[] files = new File(dir).listFiles();
            Arrays.sort(files, 
                Comparator.comparingLong(File::lastModified).reversed()
            );
            File lastFile = files[0];
            Date fileDate = new Date(lastFile.lastModified());
            String fileDay = new SimpleDateFormat("Y-M-d").format(fileDate);
            String today = new SimpleDateFormat("Y-M-d").format(new Date());

            if (today.equals(fileDay)) {
                System.out.println(dir + " modified today at " + fileDate);
                break;
            }

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {e.printStackTrace();}
        }
    }
}



  Last update: 201 days ago