【问题标题】:Retrieve files from a folder: largest, latest irrespective of the date从文件夹中检索文件:最大、最新,与日期无关
【发布时间】:2016-09-30 15:25:38
【问题描述】:

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

  1. 取最大的文件
  2. 如果文件大小相同,则取最新的。

到目前为止,我已经尝试了以下方法:

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

【问题讨论】:

    标签: java file filepath


    【解决方案1】:
        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
    

    【讨论】:

    • 我会将file.length()lastModified() 调用拉到一个局部变量中。如果你能提供帮助,你不会想多次这样做。
    • 现在只需使用 Path pathValue = folderFiles.get(0).toPath();
    【解决方案2】:

    排序然后取列表中的第一项(这是未经测试的,我不在电脑前,所以你可能需要切换 f1/f2 项目并反过来做。如果你这样做可能会溢出文件大小的差异大于 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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 2019-07-20
      • 2017-08-24
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      相关资源
      最近更新 更多