从文件夹中检索文件:最大,最新,与日期无关

时间:2016-09-30 15:25:38

标签: java file filepath

我想使用以下规则从文件夹中检索文件:

  1. 获取最大的文件
  2. 如果文件大小相同,请选择最新文件。
  3. 到目前为止,我已尝试过以下内容:

    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);
        }
    }
    

2 个答案:

答案 0 :(得分:2)

    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

答案 1 :(得分:0)

排序,然后取出列表中的第一项(这是未经测试的,我不是在计算机上,因此您可能需要切换f1 / f2项目并反向执行。有&#39;如果文件大小的差异大于int或负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.