Is there any way in Java to ensure FIFO processing of files added to a folder. I am looking for a solution that is platform independent. I am currently using the listFiles() method in java.io.File to get all the files out of a directory, but I have read that it does not guarantee any order of files found using this method. I have also thought of sorting the Files based on their last modified date, but this is unreliable, and does not ensure FIFO. Does anyone have any other ideas perhaps?
I have to use Java 6, Java 7 is not an option.
The
File.listFiles()method returns the files in an unspecified platform dependent order.If the files in the directory are not going to be changed as you are processing them, then sorting the
Filelist should work.If the files in the directory are liable to change, then there is no way that you can get a “snapshot” of the files and their modification times. But you could potentially use a Java 7
WatchServiceto track directory additions and file changes, and use that to deal with changes that happen during and after the directory listing and sorting.There no equivalent to the Java 7 WatchService in Java 6. If you want that kind of thing you will either to use an external program to feed the file names to Java in the right order, or use JNI and native code to interact with to OS-level file / directory watching service.