tags:

views:

66

answers:

3

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 here.

+2  A: 

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.

Tom
A: 

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?).

jwenting
+1  A: 

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.

KMan