开发者

Ten latest files on disk

开发者 https://www.devze.com 2022-12-22 20:55 出处:网络
I need effective algorithm to keep only ten latest files on disk in particular folder to support some kind of publishing process. Only 10 files should present in this folder at any point of time. Plea

I need effective algorithm to keep only ten latest files on disk in particular folder to support some kind of publishing process. Only 10 files should present in this folder at any point of time. Please, give your advises what should be used her开发者_如何学JAVAe.


You can ask the File for the directory to listFiles, if there are more than 9 sort them by lastModified() and delete the files oldest (smallest number) to trim down to 9.


How about using a file system watcher like JNotify?

  1. Register for events that you are interested in (for instance, Created event);
  2. Mark your internal list for the number of files upon every created event.
  3. As soon as you reach the 11th file, remove the file having oldest create date.

Or use Commons JCI FileAlterationMonitor (FAM) to monitor local filesystems and get notified about changes:

ReloadingClassLoader classloader = new ReloadingClassLoader(this.getClass().getClassLoader());
ReloadingListener listener = new ReloadingListener();

listener.addReloadNotificationListener(classloader);

FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
fam.addListener(directory, listener);
fam.start();

This discussion may help you with file system watchers.


You'd have to poll the directory at regular intervals and delete everything that's older than the 10th oldest file in it. Of course that leaves open to question what the "10th oldest file" actually is. The timestamp on the file might not indicate the date/time it was added to the folder after all. So your system might actually need some independent way to keep track of files in the folder to determine when each was added, in order to delete files based on when they were put there rather than how old the file actually is.

But that's a business requirement you don't provide (do you even know it yourself?).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号