четверг, 1 июня 2017 г.

Java 8 WatchService. Windows Implementation note.

WatchService in java is service that allows to monitor the directory for changes. Here is the important notice from javadoc:
"For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted. "

But what if you need to know  which file was actually renamed. What is the old name of a file and what is the new name?

On windows there is a native support from the OS to monitor such changes. Well, take a look how this possibilities were mapped in Java. For jdk8 see the link http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/classes/sun/nio/fs/WindowsWatchService.java#l464. For lazy ones here is the method:
<code>
// Translate file change action into watch event
        private WatchEvent.Kind<?> translateActionToEvent(int action)
        {
            switch (action) {
                case FILE_ACTION_MODIFIED :
                    return StandardWatchEventKinds.ENTRY_MODIFY;

                case FILE_ACTION_ADDED :
                case FILE_ACTION_RENAMED_NEW_NAME :
                    return StandardWatchEventKinds.ENTRY_CREATE;

                case FILE_ACTION_REMOVED :
                case FILE_ACTION_RENAMED_OLD_NAME :
                    return StandardWatchEventKinds.ENTRY_DELETE;

                default :
                    return null;  // action not recognized
            }
        }
</code>

You see, renamed and new file events mapped to ENTRY_CREATE event. The only question comes to my mind is -- why? Why it was done like this?
I think they were trying to make a universal solution, but.. why they didn't make it extensible?

Комментариев нет:

Отправить комментарий