List of usage examples for java.nio.file StandardWatchEventKinds ENTRY_CREATE
WatchEvent.Kind ENTRY_CREATE
To view the source code for java.nio.file StandardWatchEventKinds ENTRY_CREATE.
Click Source Link
From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java
@SuppressWarnings("unchecked") @Test//from www.ja v a 2 s. c o m public void logAndRotateAndPurge() throws Exception { clean("target/ArchivingTestPurge-" + format + "/logs"); final AtomicReference<String> today = new AtomicReference<>(); final Map<String, String> config = new HashMap<>(); // initial config today.set("2015-09-01"); config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log"); config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives"); config.put("archiveFormat", format); config.put("archiveOlderThan", "1 s"); config.put("purgeOlderThan", "2 s"); config.put("limit", "10 kilobytes"); config.put("level", "INFO"); config.put("dateCheckInterval", "1 second"); final LocalFileHandler handler = new LocalFileHandler() { @Override protected String currentDate() { return today.get(); } @Override protected String getProperty(final String name, final String defaultValue) { final String s = config.get(name.substring(name.lastIndexOf('.') + 1)); return s != null ? s : defaultValue; } }; final String string10chars = "abcdefghij"; final int iterations = 950; for (int i = 0; i < iterations; i++) { handler.publish(new LogRecord(Level.INFO, string10chars)); } today.set("2015-09-02"); try { Thread.sleep(2000); } catch (final InterruptedException e) { Thread.interrupted(); } final File logArchive = new File( "target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format); final File parentFile = logArchive.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { Assert.fail("Unable to create: " + parentFile); } final Path dir = parentFile.toPath(); final WatchService watcher = FileSystems.getDefault().newWatchService(); final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY); latch.set(new CountDownLatch(1)); watch(key); handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS)); final WatchEvent<?> watchEvent = lastEvent.get(); assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind())); final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent; final String io = ev.context().toString(); assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format)); today.set("2015-09-03"); try { Thread.sleep(2500); } catch (final InterruptedException e) { Thread.interrupted(); } handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the purging handler.close(); withRetry(10, 2, new Runnable() { @Override public void run() { assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists()); } }); }
From source file:de.elomagic.carafile.client.CaraCloud.java
private void registerDefaultWatch(final Path path) throws IOException { path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); }
From source file:com.iorga.iraj.servlet.AgglomeratorServlet.java
private long searchAndAppendAfter(final ServletConfig config, final Element agglomerateElement, final String scriptSrc, final String pathPrefix, final String pathSuffix, final String urlAttribute, long lastModified) throws MalformedURLException, IOException, URISyntaxException { if (mode == Mode.DEVELOPMENT) { // add a watch for that directory final Path path = Paths.get(config.getServletContext().getRealPath(scriptSrc)); path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); }/*www .j av a 2 s .com*/ final Set<String> childrenPaths = config.getServletContext().getResourcePaths(scriptSrc); for (final String path : childrenPaths) { if (path.endsWith(pathSuffix)) { // add that JS final StringBuilder targetScript = new StringBuilder("<"); targetScript.append(agglomerateElement.tagName()); // copy all the origin attributes for (final Attribute attribute : agglomerateElement.attributes()) { final String key = attribute.getKey(); if (!ATTRIBUTE_NAME.equalsIgnoreCase(key) && !urlAttribute.equalsIgnoreCase(key) && !URL_ATTRIBUTE_ATTRIBUTE_NAME.equalsIgnoreCase(key)) { targetScript.append(" ").append(attribute.html()); } } // specify the src path final String childUrl = StringUtils.removeStart(path, pathPrefix); targetScript.append(" ").append(new Attribute(urlAttribute, childUrl).html()).append(" />"); agglomerateElement.after(targetScript.toString()); lastModified = Math.max( config.getServletContext().getResource(childUrl).openConnection().getLastModified(), lastModified); } else if (path.endsWith("/")) { // it's a directory, recurse search & append lastModified = Math.max(searchAndAppendAfter(config, agglomerateElement, path, pathPrefix, pathSuffix, urlAttribute, lastModified), lastModified); } } return lastModified; }
From source file:com.sludev.mssqlapplylog.MSSQLApplyLog.java
@Override public Integer call() throws Exception { Integer res = 0;/*ww w . j a v a 2s . c om*/ String backupDirStr = config.getBackupDirStr(); String fullBackupPathStr = config.getFullBackupPathStr(); String fullBackupDatePatternStr = config.getFullBackupDatePatternStr(); String laterThanStr = config.getLaterThanStr(); String fullBackupPatternStr = config.getFullBackupPatternStr(); String logBackupPatternStr = config.getLogBackupPatternStr(); String logBackupDatePatternStr = config.getLogBackupDatePatternStr(); String sqlHost = config.getSqlHost(); String sqlDb = config.getSqlDb(); String sqlUser = config.getSqlUser(); String sqlPass = config.getSqlPass(); String sqlURL = config.getSqlUrl(); String sqlProcessUser = config.getSqlProcessUser(); boolean useLogFileLastMode = BooleanUtils.isTrue(config.getUseLogFileLastMode()); boolean doFullRestore = BooleanUtils.isTrue(config.getDoFullRestore()); boolean monitorLogBackupDir = BooleanUtils.isTrue(config.getMonitorLogBackupDir()); Path backupsDir = null; Instant laterThan = null; Path fullBackupPath = null; // Validate the Log Backup Directory if (StringUtils.isBlank(backupDirStr)) { LOGGER.error("Invalid blank/empty backup directory"); return 1; } try { backupsDir = Paths.get(backupDirStr); } catch (Exception ex) { LOGGER.error(String.format("Error parsing Backup Directory '%s'", backupDirStr), ex); return 1; } if (Files.notExists(backupsDir)) { LOGGER.error(String.format("Invalid non-existant backup directory '%s'", backupsDir)); return 1; } if (StringUtils.isBlank(logBackupPatternStr)) { LOGGER.warn(String.format( "\"Log Backup Pattern\" cannot be empty. Defaulting to " + "%s regex in backup directory", DEFAULT_LOG_FILE_PATTERN_STR)); logBackupPatternStr = DEFAULT_LOG_FILE_PATTERN_STR; } if (StringUtils.isNoneBlank(fullBackupPathStr)) { fullBackupPath = Paths.get(fullBackupPathStr); if (Files.notExists(fullBackupPath) || Files.isRegularFile(fullBackupPath) == false) { LOGGER.error(String.format("Invalid Full Backup file '%s'", backupDirStr)); return 1; } } if (StringUtils.isNoneBlank(fullBackupDatePatternStr) && StringUtils.isBlank(laterThanStr) && fullBackupPath != null) { // Retrieve the "Later Than" date from the full backup file name laterThan = FSHelper.getTimestampFromFilename(fullBackupPatternStr, fullBackupDatePatternStr, 1, fullBackupPath); if (laterThan == null) { LOGGER.error("'Later Than' cannot be null"); return 1; } } else { // Use the "Later Than" timestamp from the command line or properties // file. try { laterThan = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(laterThanStr)); } catch (Exception ex) { LOGGER.error(String.format("Error parsing 'Later Than' time '%s'", laterThanStr), ex); } } try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); } catch (ClassNotFoundException ex) { LOGGER.error("Error loading SQL Server driver [ net.sourceforge.jtds.jdbc.Driver ]", ex); return 1; } if (StringUtils.isBlank(sqlURL)) { // Build the SQL URL sqlURL = String.format("jdbc:jtds:sqlserver://%s;DatabaseName=master", sqlHost); } Properties props = new Properties(); props.setProperty("user", sqlUser); props.setProperty("password", sqlPass); try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) { if (conn == null) { LOGGER.error("Connection to MSSQL failed."); return 1; } if (doFullRestore) { LOGGER.info(String.format("\nStarting full restore of '%s'...", fullBackupPathStr)); StopWatch sw = new StopWatch(); sw.start(); String strDevice = fullBackupPathStr; String query = String.format("RESTORE DATABASE %s FROM DISK='%s' WITH NORECOVERY, REPLACE", sqlDb, strDevice); Statement stmt = null; try { stmt = conn.createStatement(); } catch (SQLException ex) { LOGGER.debug("Error creating statement", ex); return 1; } try { boolean sqlRes = stmt.execute(query); } catch (SQLException ex) { LOGGER.error(String.format("Error executing...\n'%s'", query), ex); return 1; } sw.stop(); LOGGER.debug(String.format("Query...\n'%s'\nTook %s", query, sw.toString())); } } catch (SQLException ex) { LOGGER.error("SQL Exception restoring the full backup", ex); } // Filter the log files. // Loop multiple times to catch new logs that have been transferred // while we process. List<Path> files = null; do { try { files = FSHelper.listLogFiles(backupsDir, laterThan, useLogFileLastMode, logBackupPatternStr, logBackupDatePatternStr, files); } catch (IOException ex) { LOGGER.error("Log Backup file filter/sort failed", ex); return 1; } if (files == null || files.isEmpty()) { LOGGER.debug("No Log Backup files found this iteration."); continue; } StringBuilder msg = new StringBuilder(); for (Path file : files) { msg.append(String.format("file : '%s'\n", file)); } LOGGER.debug(msg.toString()); // Restore all log files try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) { for (Path p : files) { try { MSSQLHelper.restoreLog(p, sqlProcessUser, sqlDb, conn); } catch (SQLException ex) { LOGGER.error(String.format("SQL Exception restoring the log backup '%s'", p), ex); } } } catch (SQLException ex) { LOGGER.error("SQL Exception restoring the log backup", ex); } } while (files != null && files.isEmpty() == false); if (monitorLogBackupDir) { // Watch for new log files List<Path> paths = new ArrayList(); paths.add(backupsDir); final Watch watch; final String currSQLDb = sqlDb; final String currSQLProcUser = sqlProcessUser; final String currSQLURL = sqlURL; final String currLogBackupPatternStr = logBackupPatternStr; try { watch = Watch.from(paths); watch.processEvents((WatchEvent<Path> event, Path path) -> { int watchRes = 0; if (event.kind() != StandardWatchEventKinds.ENTRY_CREATE) { return watchRes; } Pattern fileMatcher = Pattern.compile(currLogBackupPatternStr); if (fileMatcher.matcher(path.getFileName().toString()).matches()) { try (Connection conn = MSSQLHelper.getConn(currSQLURL, props)) { MSSQLHelper.restoreLog(path, currSQLProcUser, currSQLDb, conn); } catch (SQLException ex) { // There's really no recovering from a failed log backup LOGGER.error("SQL Exception restoring the log backup", ex); System.exit(1); } } return watchRes; }); } catch (IOException | FileCheckException ex) { LOGGER.error(String.format("Error watching backup directory...\n'%s'", backupsDir), ex); return 1; } catch (InterruptedException ex) { LOGGER.info(String.format("Interrupted watching backup directory...\n'%s'", backupsDir), ex); } } return res; }
From source file:org.springframework.cloud.config.monitor.FileMonitorConfiguration.java
private void registerWatch(Path dir) throws IOException { if (log.isDebugEnabled()) { log.debug("registering: " + dir + " for file creation events"); }//from w ww.ja v a 2 s .c o m try { dir.register(this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("Cannot register watcher for " + dir, e); } }
From source file:ddf.camel.component.catalog.content.ContentProducerDataAccessObjectTest.java
@Test public void testCreateContentItem() throws Exception { File testFile = temporaryFolder.newFile("testCreateContentItem.txt"); // make sample list of metacard and set of keys List<MetacardImpl> metacardList = ImmutableList.of(new MetacardImpl()); String uri = testFile.toURI().toASCIIString(); Set<String> keys = new HashSet<>(Collections.singletonList(String.valueOf(DigestUtils.sha1Hex(uri)))); // mock out responses for create, delete, update CreateResponse mockCreateResponse = mock(CreateResponse.class); doReturn(metacardList).when(mockCreateResponse).getCreatedMetacards(); DeleteResponse mockDeleteResponse = mock(DeleteResponse.class); doReturn(metacardList).when(mockDeleteResponse).getDeletedMetacards(); UpdateResponse mockUpdateResponse = mock(UpdateResponse.class); doReturn(metacardList).when(mockUpdateResponse).getUpdatedMetacards(); // setup mockFileSystemPersistenceProvider FileSystemPersistenceProvider mockFileSystemPersistenceProvider = mock(FileSystemPersistenceProvider.class); doReturn(keys).when(mockFileSystemPersistenceProvider).loadAllKeys(); doAnswer(invocationOnMock -> keys.remove(invocationOnMock.getArguments()[0])) .when(mockFileSystemPersistenceProvider).delete(anyString()); doReturn("sample").when(mockFileSystemPersistenceProvider).loadFromPersistence(any(String.class)); // setup mockCatalogFramework CatalogFramework mockCatalogFramework = mock(CatalogFramework.class); doReturn(mockCreateResponse).when(mockCatalogFramework).create(any(CreateStorageRequest.class)); doReturn(mockDeleteResponse).when(mockCatalogFramework).delete(any(DeleteRequest.class)); // setup mockSourceInfo SourceInfoResponse mockSourceInfoResponse = mock(SourceInfoResponse.class); SourceDescriptor mockSourceDescriptor = mock(SourceDescriptor.class); when(mockSourceDescriptor.isAvailable()).thenReturn(true); when(mockSourceInfoResponse.getSourceInfo()).thenReturn(Collections.singleton(mockSourceDescriptor)); when(mockCatalogFramework.getSourceInfo(any(SourceInfoRequest.class))).thenReturn(mockSourceInfoResponse); // setup mockComponent ContentComponent mockComponent = mock(ContentComponent.class); doReturn(mockCatalogFramework).when(mockComponent).getCatalogFramework(); // setup mockEndpoint ContentEndpoint mockEndpoint = mock(ContentEndpoint.class); doReturn(mockComponent).when(mockEndpoint).getComponent(); WatchEvent.Kind<Path> kind; String mimeType = "txt"; Map<String, Object> headers = new HashedMap(); Map<String, Serializable> attributeOverrides = new HashMap<>(); attributeOverrides.put("example", ImmutableList.of("something", "something1")); attributeOverrides.put("example2", ImmutableList.of("something2")); headers.put(Constants.ATTRIBUTE_OVERRIDES_KEY, attributeOverrides); headers.put(Constants.STORE_REFERENCE_KEY, uri); kind = StandardWatchEventKinds.ENTRY_CREATE; contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile, kind, mimeType, headers);/* w w w .jav a2 s . c o m*/ verify(mockCatalogFramework).create(any(CreateStorageRequest.class)); kind = StandardWatchEventKinds.ENTRY_MODIFY; contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile, kind, mimeType, headers); verify(mockCatalogFramework).update(any(UpdateStorageRequest.class)); kind = StandardWatchEventKinds.ENTRY_DELETE; contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile, kind, mimeType, headers); verify(mockCatalogFramework).delete(any(DeleteRequest.class)); contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile, kind, mimeType, headers); verify(mockCatalogFramework).delete(any(DeleteRequest.class)); }
From source file:MonitorSaurausRex.MainMenu.java
public boolean MonitorDirectory() { Path directory = Paths.get("C:/Users/" + user + "/Documents/"); try {//w w w .j a v a 2 s . c o m WatchService fileSystemWatchService = FileSystems.getDefault().newWatchService(); WatchKey watchKey = directory.register(fileSystemWatchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); testTimer = new TimerTask() { @Override public void run() { checkPause = true; test = changeCheck(); if (test) { testTimer.cancel(); System.out.println("Quaritnen sucsessfully activates"); } } }; Timer timer = new Timer(); timer.schedule(testTimer, 0, 1000); while (true) { WatchKey watchKeyActual = fileSystemWatchService.take(); for (WatchEvent<?> event : watchKeyActual.pollEvents()) { WatchEvent.Kind<?> eventKind = event.kind(); if (eventKind == StandardWatchEventKinds.OVERFLOW) { continue; } WatchEvent<Path> eventPath = (WatchEvent<Path>) event; Path fileName = eventPath.context(); //timerCheck(); ????? //http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java // boolean test = false; if (checkPause == false) { checkPause = true; } else { ChangeCounter++; System.out.println("Event " + eventKind + " occurred on " + fileName); } if (test) break; } boolean isReset = watchKeyActual.reset(); if (!isReset || test) { break; } } } catch (IOException | InterruptedException ioe) { } return true; /// EXIT METHOD }
From source file:erigo.filewatch.FileWatch.java
/** * Creates a WatchService and registers the given directory *//*from w w w . jav a2 s .co m*/ // FileWatch(Path watchDir, String outputFilename, Path outputDirI) throws IOException { FileWatch(String[] argsI) throws IOException { // // Parse command line arguments // // 1. Setup command line options // Options options = new Options(); // Boolean options (only the flag, no argument) options.addOption("h", "help", false, "Print this message."); options.addOption("a", "adjust_latency", false, "Divide latency results by 2 because test data files are from a recaster (round-trip)."); options.addOption("d", "disp_recaster", false, "Display results when operating in recaster mode."); // Command line options that include an argument Option nextOption = Option.builder("i").argName("watchdir").hasArg().desc( "Directory to watch for incoming test data files (must be an existing directory); default = \"" + DEFAULT_WATCH_DIR + "\".") .build(); options.addOption(nextOption); nextOption = Option.builder("o").argName("outfilename").hasArg() .desc("Name of the output metrics data file; must be a new file.").build(); options.addOption(nextOption); nextOption = Option.builder("p").argName("pollinterval_msec").hasArg().desc( "Watch for new files by polling (don't use Java WatchService); sleep for <pollinterval_msec> (milliseconds) between scans.") .build(); options.addOption(nextOption); nextOption = Option.builder("r").argName("recasterdir").hasArg() .desc("Recast test data files to the specified output directory (must be an existing directory).") .build(); options.addOption(nextOption); nextOption = Option.builder("t").argName("plottitle").hasArg() .desc("Custom title for throughput and latency plots.").build(); options.addOption(nextOption); // // 2. Parse command line options // CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argsI); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // // 3. Retrieve the command line values // if (line.hasOption("h")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp("FileWatch", options); return; } bAdjustLatencyMetrics = line.hasOption("a"); bOutputResultsInRecastMode = line.hasOption("d"); // Watch directory String watchDirName = line.getOptionValue("i", DEFAULT_WATCH_DIR); Path watchDir = Paths.get(watchDirName); if (!watchDir.toFile().isDirectory()) { System.err.println("\nThe given watch directory does not exist."); System.exit(-1); } // Recaster directory Path outputDirPath = null; String outputDirName = line.getOptionValue("r"); if (outputDirName != null) { outputDirPath = Paths.get(outputDirName); if (!outputDirPath.toFile().isDirectory()) { System.err.println("\nThe given recaster output directory does not exist."); System.exit(-1); } // Make sure watchDir and outputDir aren't the same if (watchDir.toAbsolutePath().compareTo(outputDirPath.toAbsolutePath()) == 0) { System.err.println("\nThe recaster output directory cannot be the same as the watch directory."); System.exit(-1); } bRecast = true; outputDir = outputDirPath.toFile(); } // Output filename String outputFilename = line.getOptionValue("o"); if ((outputFilename == null) && (!bRecast || bOutputResultsInRecastMode)) { System.err.println("\nMust specify the name of the output data file."); System.exit(-1); } if (outputFilename != null) { File outputFile = new File(outputFilename); if (outputFile.isDirectory()) { System.err.println( "\nThe given output data file is the name of a directory; must specify an output filename."); System.exit(-1); } else if (outputFile.isFile()) { System.err.println( "\nThe given output data file is the name of an existing file; must specify a new filename."); System.exit(-1); } } // Use polling to check for new files? String pollIntervalStr = line.getOptionValue("p"); if (pollIntervalStr != null) { try { pollInterval = Integer.parseInt(pollIntervalStr); if ((pollInterval <= 0) || (pollInterval > 1000)) { throw new NumberFormatException("Illegal value"); } } catch (NumberFormatException nfe) { System.err.println("\nPoll interval must be an integer in the range 0 < x <= 1000"); System.exit(-1); } } // Title for the throughput and latency plots customPlotTitle = line.getOptionValue("t", ""); // Make sure "end.txt" doesn't already exist in the directory; this file is our signal // that we're done processing File endFile = new File(watchDir.toFile(), "end.txt"); if (endFile.exists()) { System.err.println("\nMust delete \"" + endFile + "\" before running test."); System.exit(-1); } // If we are recasting, make sure "end.txt" doesn't exist in the output directory either if (outputDirPath != null) { endFile = new File(outputDirPath.toFile(), "end.txt"); if (endFile.exists()) { System.err.println("\nMust delete \"" + endFile + "\" in output directory before running test."); System.exit(-1); } } if (pollInterval > 0) { System.err .println("\nWatching directory \"" + watchDir + "\" for incoming files; using polling method"); processEvents_polling(watchDir.toFile()); } else { // Register the directory with the WatchService // Only collect data for ENTRY_CREATE events. Even if a file is just // copied into a directory, several ENTRY_MODIFY events can be // triggered because the file's content and its parameters (such as // timestamp) are independently set. watchDir.register(watcher, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE }, SensitivityWatchEventModifier.HIGH); System.err.println( "\nWatching directory \"" + watchDir + "\" for incoming files; using WatchService events"); processEvents_watchservice(); watcher.close(); } if (!bRecast || bOutputResultsInRecastMode) { System.err.println("\nWrite data to file \"" + outputFilename + "\"..."); } processData(outputFilename); System.err.println( "\nFileWatch received a total of " + num_received_files + " files (not including \"end.txt\")"); System.err .println("In processing, " + num_skipped_files + " files were skipped (due to wrong name format)"); int num_files_processed = num_received_files - num_skipped_files; System.err.println( "Thus, a total of " + num_files_processed + " files with properly formatted names were processed"); System.err.println("\nTest is complete."); }
From source file:org.flowerplatform.web.git.GitUtils.java
public void listenForChanges(File file) throws IOException { Path path = file.toPath();//from w w w. j a v a 2s. com if (file.isDirectory()) { WatchService ws = path.getFileSystem().newWatchService(); path.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); WatchKey watch = null; while (true) { System.out.println("Watching directory: " + file.getPath()); try { watch = ws.take(); } catch (InterruptedException ex) { System.err.println("Interrupted"); } List<WatchEvent<?>> events = watch.pollEvents(); if (!watch.reset()) { break; } for (WatchEvent<?> event : events) { Kind<Path> kind = (Kind<Path>) event.kind(); Path context = (Path) event.context(); if (kind.equals(StandardWatchEventKinds.OVERFLOW)) { System.out.println("OVERFLOW"); } else if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) { System.out.println("Created: " + context.getFileName()); } else if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) { System.out.println("Deleted: " + context.getFileName()); } else if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) { System.out.println("Modified: " + context.getFileName()); } } } } else { System.err.println("Not a directory. Will exit."); } }