The watch service should fit your needs: https://docs.oracle.com/javase/tutorial/essential/io/notification.html
The following are the basic steps necessary to implement the watch service:
- Create a WatchService "watcher" for the file system.
- For each directory that you want to control, register it with an observer. When registering a directory, you specify the type of events for which notification is required. You get a WatchKey instance for each registered directory.
- Implement an infinite loop to wait for incoming events. When an event occurs, the key is signaled and placed in the observer queue. Remove the key from the observer queue. You can get the file name from the key.
- Get each pending event for a key (there may be several events) and process as necessary.
- Reset the key and resume waiting for events.
- Close service: the watch service ends when the thread exits or closes (by calling its private method).
As an additional note, you should approve the java.nio package, available since the transition of Java files to Java 7.
renameTo() has some serious limitations (extracted from Javadoc):
Many aspects of the behavior of this method are inherently platform-dependent: the renaming operation may not be a file from one file system to another, it may not be atomic, or it may not work if a file with the target destination name already exists. You always need to check the return value to make sure that the rename operation is successful.
For example, on Windows, renameTo() may fail if the target directory exists, even if it is empty.
Additionally, a method can return a boolean when it fails instead of throwing an exception.
Thus, it can be difficult to guess the origin of the problem and process it in code.
Here is a simple class that fulfills your requirement (it handles all the steps, but closing the Watch Service is not necessary).
package watch; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import java.io.File; 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.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.Date; import java.util.HashMap; import java.util.Map; public class WatchDir { private final WatchService watcher; private final Map<WatchKey, Path> keys; private Path targetDirPath; private Path sourceDirPath; WatchDir(File sourceDir, File targetDir) throws IOException { this.watcher = FileSystems.getDefault().newWatchService(); this.keys = new HashMap<WatchKey, Path>(); this.sourceDirPath = Paths.get(sourceDir.toURI()); this.targetDirPath = Paths.get(targetDir.toURI()); WatchKey key = sourceDirPath.register(watcher, ENTRY_CREATE); keys.put(key, sourceDirPath); } public static void main(String[] args) throws IOException {
source share