2016-09-30 63 views
1

我想使用以下規則從文件夾中檢索文件:檢索文件:最大的,最新的,不論日期

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

回答

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 
+0

我想將'file.length()'和'lastModified()'調用到局部變量中。如果你可以幫助你,你不會想多次做這些事情。 – Gray

+0

現在只需使用Path pathValue = folderFiles.get(0).toPath(); – user2501165

0

排序,然後採取的第一項在列表中(這是未經測試,我不是在電腦前,所以你可能必須切換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.