Java directory monitoring program

Hi guys, I want to create a program that controls the 24/7 directory, and if a new file is added to it, it should sort it if the file is more than 10 MB. I have implemented the code for my directory, but I do not know how to get it to check the directory every time a new entry is added, as this should happen continuously.

import java.io.*; import java.util.Date; public class FindingFiles { public static void main(String[] args) throws Exception { File dir = new File("C:\\Users\\Mayank\\Desktop\\java princeton");// Directory that contain the files to be searched File[] files= dir.listFiles(); File des=new File("C:\\Users\\Mayank\\Desktop\\newDir"); // new directory where files are to be moved if(!des.exists()) des.mkdir(); for(File f : files ){ long diff = new Date().getTime() - f.lastModified(); if( (f.length() >= 10485760) || (diff > 10 * 24 * 60 * 60 * 1000) ) { f.renameTo(new File("C:\\Users\\mayank\\Desktop\\newDir\\"+f.getName())); } } } } 
+5
source share
1 answer

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 { // Directory that contain the files to be searched File dir = new File("C:\\Users\\Mayank\\Desktop\\java princeton"); // new directory where files are to be moved File des = new File("C:\\Users\\Mayank\\Desktop\\newDir"); if (!des.exists()) des.mkdir(); // register directory and process its events new WatchDir(dir, des).processEvents(); } /** * Process all events for keys queued to the watcher * * @throws IOException */ private void processEvents() throws IOException { for (;;) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); // Context for directory entry event is the file name of entry @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path name = ev.context(); Path child = dir.resolve(name); // print out event System.out.format("%s: %s\n", event.kind().name(), child); // here is a file or a folder modified in the folder File fileCaught = child.toFile(); // here you can invoke the code that performs the test on the // size file and that makes the file move long diff = new Date().getTime() - fileCaught.lastModified(); if (fileCaught.length() >= 10485760 || diff > 10 * 24 * 60 * 60 * 1000) { System.out.println("rename done for " + fileCaught.getName()); Path sourceFilePath = Paths.get(fileCaught.toURI()); Path targetFilePath = targetDirPath.resolve(fileCaught.getName()); Files.move(sourceFilePath, targetFilePath); } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { keys.remove(key); // all directories are inaccessible if (keys.isEmpty()) { break; } } } } } 
+2
source

Source: https://habr.com/ru/post/1265358/


All Articles