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

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

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

相关标签:
9条回答
  • 2020-11-28 10:19
    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;
    }
    

    This works great for me

    0 讨论(0)
  • 2020-11-28 10:19

    Your problem is similar to: How to get only 10 last modified files from directory using Java?

    Just change the filter code to have only one File and the accept method should simply compare the two time stamps.

    Untested code:

         class TopFileFilter implements FileFilter {
    
            File topFile;
    
            public boolean accept(File newF) {
                if(topFile == null)
                    topFile = newF;
                else if(newF.lastModified()>topFile.lastModified())
                    topFile = newF;
                return false;
            }
    
        }
    

    Now, call dir.listFiles with an instance of this filter as argument. At the end, the filter.topFile is the last modified file.

    0 讨论(0)
  • 2020-11-28 10:19

    The comparator in Emil's solution would be cleaner this way

    public int compare(File a, File b) {
        if ((a.lastModified() < b.lastModified())) {
            return 1;
        } else if ((a.lastModified() > b.lastModified())) {
            return -1;
        } 
        return 0;
    }
    

    Casting (a.lastModified() - b.lastModified()) to int can produce unexpected results.

    0 讨论(0)
  • 2020-11-28 10:19
        String path = "C:\\Work\\Input\\";
    
        File dir = new File(path);
        File[] files = dir.listFiles();
    
        Arrays.sort(files, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return Long.valueOf(f2.lastModified()).compareTo(
                        f1.lastModified());
            }
        });
    
        for (int index = 0; index < files.length; index++) {
            // Print out the name of files in the directory
            System.out.println(files[index].getName());
        }
    
    }
    
    0 讨论(0)
  • 2020-11-28 10:22

    Java 8

    Optional<Path> findLastModifiedFile(Path directory) throws IOException {
        return Files.list(directory)
                .max(this::compareLastModified);
    }
    
    int compareLastModified(Path p1, Path p2) {
        try {
            return Files.getLastModifiedTime(p1).compareTo(Files.getLastModifiedTime(p2));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 10:27

    Let's assume that the variable thePath contains the directory we want to search, the following snippet returns the last modified file inside it:

    Files.walk(thePath)
    .sorted((f1, f2) -> -(int)(f1.toFile().lastModified() - f2.toFile().lastModified()))
    .skip(1)
    .findFirst()
    

    What it does is:

    • first sort the files by their last modification time in reverse,
    • then skip the directory itself,
    • and finally take the first element in the stream (which is the last modified one).
    0 讨论(0)
提交回复
热议问题