Search code examples
javaeventswatchservice

How could I omit detection for some files with Java 7 WatchService


I've registered CREATE, MODIFY and DELETE events to the monitor successfully and they works fine to me. For my issue I would like to do some file modification like 'rename' once CREATE event is triggered so MODIFY event will be triggered next as well however I don't want it. Could I just omit MODIFY event for this time?

 if(event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE)){
                try{
                    if(!name.toString().startsWith("~")){
                            Path tempPath = Paths.get(path+"/~temp_"+name.getFileName());
                            Path oldPath = Paths.get(path+"/"+name.getFileName());
                            Files.move(oldPath, tempPath, StandardCopyOption.REPLACE_EXISTING);
                            PDFStamp.stampPDF(tempPath.toString(), oldPath.toString());
                            omitPath.put(name, name);
                            Files.delete(tempPath);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }   
            }

Solution

  • I don't think there is a way to tell the watch service temporarily ignore events. I suggest that you do it in your code.

    However, what you seem to be doing here it to create a backup of a file by having the watch service notice that you've just created the new one. But I don't think that will work. By the time your code gets the event, the old version of the file could already have been overwritten with the new one. And then your move call will move the new file to the "temp" location.

    I suggest that you get the code that creating the file to make the backup of the original one before it opens the new one. Your code will be simpler, more reliable and more likely to be portable.