How do I find the last modified file in a directory in Java?

后端 未结 9 875
半阙折子戏
半阙折子戏 2020-11-28 09:51

How do I find the last modified file in a directory in java?

相关标签:
9条回答
  • 2020-11-28 10:35

    Combine these two:

    1. You can get the last modified time of a File using File.lastModified().
    2. To list all of the files in a directory, use File.listFiles().

    Note that in Java the java.io.File object is used for both directories and files.

    0 讨论(0)
  • 2020-11-28 10:37
    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-11-28 10:43

    You can retrieve the time of the last modification using the File.lastModified() method. My suggested solution would be to implement a custom Comparator that sorts in lastModified()-order and insert all the Files in the directory in a TreeSet that sorts using this comparator.

    Untested example:

    SortedSet<File> modificationOrder = new TreeSet<File>(new Comparator<File>() {
        public int compare(File a, File b) {
            return (int) (a.lastModified() - b.lastModified());
        }
    });
    
    for (File file : myDir.listFiles()) {
        modificationOrder.add(file);
    }
    
    File last = modificationOrder.last();
    

    The solution suggested by Bozho is probably faster if you only need the last file. On the other hand, this might be useful if you need to do something more complicated.

    0 讨论(0)
提交回复
热议问题