Java - get the newest file in a directory?

后端 未结 9 1357
难免孤独
难免孤独 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:35
    private File getLatestFilefromDir(String dirPath){
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            return null;
        }
    
        File lastModifiedFile = files[0];
        for (int i = 1; i < files.length; i++) {
           if (lastModifiedFile.lastModified() < files[i].lastModified()) {
               lastModifiedFile = files[i];
           }
        }
        return lastModifiedFile;
    }
    
    0 讨论(0)
  • 2020-12-01 02:36

    Something like:

    import java.io.File;
    import java.util.Arrays;
    import java.util.Comparator;
    
    
    public class Newest {
        public static void main(String[] args) {
            File dir = new File("C:\\your\\dir");
            File [] files  = dir.listFiles();
            Arrays.sort(files, new Comparator(){
                public int compare(Object o1, Object o2) {
                    return compare( (File)o1, (File)o2);
                }
                private int compare( File f1, File f2){
                    long result = f2.lastModified() - f1.lastModified();
                    if( result > 0 ){
                        return 1;
                    } else if( result < 0 ){
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            System.out.println( Arrays.asList(files ));
        }
    }
    
    0 讨论(0)
  • 2020-12-01 02:40

    This will return the most recent created file, I made this because when you create a file in some situations, it may not always have the correct modified date.

    import java.nio.file.Files;
    import java.nio.file.attribute.BasicFileAttributes;
    import java.nio.file.attribute.FileTime;
    
    private File lastFileCreated(String dir) {
        File fl = new File(dir);
        File[] files = fl.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return true;
            }
        });
    
        FileTime lastCreated = null;
        File choice = null;
    
        for (File file : files) {
            BasicFileAttributes attr=null;
            try {
                attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            }catch (Exception e){
                System.out.println(e);
            }
    
            if(lastCreated ==null)
                lastCreated = attr.creationTime();
    
            if (attr!=null&&attr.creationTime().compareTo(lastCreated)==0) {
                choice = file;
            }
        }
        return choice;
    }
    
    0 讨论(0)
提交回复
热议问题