Java - get the newest file in a directory?

后端 未结 9 1387
难免孤独
难免孤独 2020-12-01 02:13

Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?

9条回答
  •  眼角桃花
    2020-12-01 02:34

    This works perfectly fine for me:

    import org.apache.commons.io.FileUtils;
    import org.apache.commons.io.comparator.LastModifiedFileComparator;
    import org.apache.commons.io.filefilter.WildcardFileFilter;
    
    ...
    
    /* Get the newest file for a specific extension */
    public File getTheNewestFile(String filePath, String ext) {
        File theNewestFile = null;
        File dir = new File(filePath);
        FileFilter fileFilter = new WildcardFileFilter("*." + ext);
        File[] files = dir.listFiles(fileFilter);
    
        if (files.length > 0) {
            /** The newest file comes first **/
            Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
            theNewestFile = files[0];
        }
    
        return theNewestFile;
    }
    

提交回复
热议问题