1

I want to sort the files in directory as oldest first in java to perform some opertion on files in (FIFO principle). For this i am using lastmodified method on each flie object and then comapring them through a comparator which gives me the sorted list like below

    public static ArrayList<File> sortListAscending(ArrayList<File> list) {
    Collections.sort(list, new Comparator<File>() {
        public int compare(final File o1, final File o2) {
            return new Long(((File) o1).lastModified()).compareTo(new Long(
                    ((File) o2).lastModified()));
        }
    });
    return list;
}

When i run this on windows i get a 13 digit timestamp returned , while in unix timestamp is not upto milliseconds . So the above method fails in unix for the files which came in directory in that one second time frame.

Please suggest some work around ?

6
  • You need to use some additional information such as the filename or the original position in the directory. Sep 7, 2012 at 9:28
  • @PeterLawrey Thanks for response , so as suggested by you to include filename so am i supposed follow a particular pattern in filename for eg alphabetical order and check that order also? Sep 7, 2012 at 10:39
  • Yes, if there are details in the filename which are not recorded in the second based timestamp. Sep 7, 2012 at 10:44
  • Thanks Peter i think this only seems to be a final workaround. being a newbie to aix i am still confused that if system does not store last modified timestamp upto millisecond then how come ls -lt is producing a valid result. Sep 7, 2012 at 10:55
  • It is likely that it preserves the order in the directory if the timestamps are the same (another one of my suggestions ;) If you add files to a directory, they are likely to appear in the order you added them which can look about right. Sep 7, 2012 at 10:57

1 Answer 1

0

On my Ubuntu machine timestamp is returned in 13 digit ie. Miliseconds. can you check if system clock is set correctly on your linux machine.

So you can apply comparison in seconds.

long lastModified1 = (o1.lastModified()/1000)
long lastModified2 = (o2.lastModified()/1000)

return Long.valueOf(lastModified1).compareTo(lastModified2);
3
  • Hi amit , timestamp returned in aix is also of 13 digit but the last 3 digits are always 0 for every file . Can u make sure that file modified timestamp has valid miliseconds values in your case ? Sep 7, 2012 at 10:34
  • So you can ignore comparison in ms by rounding it. Sep 7, 2012 at 11:01
  • Method which i used is still good with comapring seconds so i am worried about the files for same seconds only . :-) Sep 7, 2012 at 11:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.