Best way to list files in Java, sorted by Date Modified?

后端 未结 17 884
-上瘾入骨i
-上瘾入骨i 2020-11-22 11:51

I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list ba

17条回答
  •  囚心锁ツ
    2020-11-22 12:21

    This might be faster if you have many files. This uses the decorate-sort-undecorate pattern so that the last-modified date of each file is fetched only once rather than every time the sort algorithm compares two files. This potentially reduces the number of I/O calls from O(n log n) to O(n).

    It's more code, though, so this should only be used if you're mainly concerned with speed and it is measurably faster in practice (which I haven't checked).

    class Pair implements Comparable {
        public long t;
        public File f;
    
        public Pair(File file) {
            f = file;
            t = file.lastModified();
        }
    
        public int compareTo(Object o) {
            long u = ((Pair) o).t;
            return t < u ? -1 : t == u ? 0 : 1;
        }
    };
    
    // Obtain the array of (file, timestamp) pairs.
    File[] files = directory.listFiles();
    Pair[] pairs = new Pair[files.length];
    for (int i = 0; i < files.length; i++)
        pairs[i] = new Pair(files[i]);
    
    // Sort them by timestamp.
    Arrays.sort(pairs);
    
    // Take the sorted pairs and extract only the file part, discarding the timestamp.
    for (int i = 0; i < files.length; i++)
        files[i] = pairs[i].f;
    

提交回复
热议问题