Java examples for File Path IO:File Watcher
Watch for an image folder
import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) throws Exception { final Path path = Paths.get("C:/security"); WatchService watchService = FileSystems.getDefault().newWatchService(); path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); OUTERMOST: while (true) { WatchKey key = watchService.poll(11, TimeUnit.SECONDS); if (key == null) { System.out.println("canceled!"); break;/*www .j av a2 s.c o m*/ } else { for (WatchEvent<?> watchEvent : key.pollEvents()) { Kind<?> kind = watchEvent.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; Path filename = watchEventPath.context(); Path child = path.resolve(filename); if (Files.probeContentType(child).equals("image/jpeg")) { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MMM-dd HH:mm:ss"); System.out.println("event: " + dateFormat.format(new Date())); } else { System.out.println("not an image"); break OUTERMOST; } } } boolean valid = key.reset(); if (!valid) { break; } } } watchService.close(); } }