简体   繁体   English

如何在Java中获取目录的最新文件

[英]How to get the most recent file of a directory in Java

Let's say that I have a specific directory on a system (specifically Ubuntu) with say backups or logs generated by other programs.假设我在系统(特别是 Ubuntu)上有一个特定目录,其中包含其他程序生成的备份或日志。 How would I locate and open the most recently created (or modified) file as a File in Java?如何在 Java 中将最近创建(或修改)的文件作为File定位并打开?

I will need a solution that does not rely on a scenario where filenames are named after a timestamp or sequential names like log1,log2, etc... .我将需要一个依赖于文件名以时间戳或顺序名称(如log1,log2, etc...命名的方案的解决方案。 Subdirectories will be ignored.子目录将被忽略。

You can loop through files for directory and compare them and find the last modified one.您可以遍历目录的文件并比较它们并找到最后修改的文件。

public File getLastModifiedFile(File directory) {
    File[] files = directory.listFiles();
   if (files.length == 0) return null;
    Arrays.sort(files, new Comparator<File>() {
        public int compare(File o1, File o2) {
            return new Long(o2.lastModified()).compareTo(o1.lastModified()); 
        }});
    return files[0];
}

To get last modified time:获取上次修改时间:

 File file = getLastModifiedTime("C:\abcd");
 long lastModified = file != null ? file.lastModified() : -1 // -1 or whatever convention you want to infer no file exists

Second answer to this question should do what you want:这个问题的第二个答案应该做你想做的:

stackoverflow.com/questions/2064694/how-do-i-find-the-last-modified-file-in-a-directory-in-java stackoverflow.com/questions/2064694/how-do-i-find-the-last-modified-file-in-a-directory-in-java

 file.lastModified()

gives you the time a specific file was last modified, you can simply get that time for every file and then loop over the times to find the "newest" time.为您提供上次修改特定文件的时间,您可以简单地获取每个文件的时间,然后循环查找“最新”时间。

Question seems to be a duplicate of the one asked in the link.问题似乎与链接中提出的问题重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM