Sort an array of files
From CodeCodex
Contents |
[edit] Implementations
[edit] Java
Sort an array of File by modification date descending.
File f = new File(path);
File [] files = f.listFiles();
Arrays.sort( files, new Comparator<File>()
{
public int compare(File o1, File o2) {
return o2.lastModified() - o1.lastModified();
}
});
Source: BigBold
[edit] OCaml
Sort an array of files by last modification date from most recent to least recent. The following implementation executes the stat function only once per file for efficiency and correctness purposes:
# let sort a =
let a' = Array.map (fun file -> (file, Unix.stat file)) a in
Array.sort (fun (_, s1) (_, s2) ->
compare s2.Unix.st_mtime s1.Unix.st_mtime) a';
Array.map fst a'
val sort : string array -> string array
We can use it to list the files of the current directory:
# sort (Sys.readdir Filename.current_dir_name);; - : string array = [| ... |]
[edit] Perl
sort {[stat $a]->[9] <=> [stat $b]->[9]} @list; # sort by mtime
[edit] Ruby
Sort an array of File by modification date descending.
dirname = "/"
Dir.chdir(dirname) do
array = Dir.entries('.').sort_by{|fname|File.mtime(fname)}.reverse
array.each {|fname| puts "#{File.mtime(fname)} : #{fname}"}
end

