user2501165
user2501165

Reputation: 191

Retrieve files from a folder: largest, latest irrespective of the date

I would like to retrieve files from a folder using the following rules:

  1. Take the largest file
  2. If files are of the same size then take the newest one.

I have tried the following so far:

List<Path> folderFilePaths = new ArrayList<Path>();

TreeMap<Date,List<Path>> filesByDay = new TreeMap<>();

for (Path filePath : folderFilePaths) {
        String fileName = filePath.toFile().getName();
        String[] fileNameParts = fileName.split("\\.");

        filesByDay.add(filePath);
}

Path largestFile = filesByDay.get(0);
for (int i=1; i<filesByDay.size(); i++){
    if (largestFile.toFile().length() < filesByDay.get(i).toFile().length()) {
        largestFile = filesByDay.get(i);
    }
}

Upvotes: 1

Views: 49

Answers (2)

Kylar
Kylar

Reputation: 9334

Sort and then take the first item in the list (This is untested, I'm not at a computer, so you may have to switch around the f1/f2 items and do it in reverse. There's a possible overflow if you have a difference in file sizes that's more than an int or negative int).

Collections.sort(folderFilePaths, (o1, o2) -> {
        File f1 = o1.toFile();
        File f2 = o2.toFile();
        long compareLength = f2.length()-f1.length();
        return (int) ((0 == compareLength) ? (f2.lastModified() - f1.lastModified()) : compareLength);

});
folderFilePaths.get(0) should have the one you want.

Upvotes: 0

LKHO
LKHO

Reputation: 106

    class Tuple<T1, T2, T3> {
        public T1 first;
        public T2 second;
        public T3 third;

        public Tuple(T1 first, T2 second, T3 third) {
            this.first = first;
            this.second = second;
            this.third = third;
        }
    }


    List<Tuple<File, Long, Long>> folderFiles = new ArrayList<Tuple<File, Long, Long>>();
    for (Path filePath : folderFilePaths) {
        File f = filePath.toFile();
        folderFiles.add(new Tuple<>(f, f.length(), f.lastModified()));
    }

    Collections.sort(folderFiles, new Comparator<Tuple<File, Long, Long>>() {
        @Override
        public int compare(Tuple<File, Long, Long> lhs, Tuple<File, Long, Long> rhs) {
            if (lhs.second == rhs.second)
                if (lhs.third == rhs.third)
                    return 0;
                else
                    return lhs.third > rhs.third ? -1 : 1;
            else
                return lhs.second > rhs.second ? -1 : 1;
        }
    });

    folderFiles.get(0).first; // the top one is the largest, or newest

Upvotes: 2

Related Questions