如何在Java目录中找到最后修改的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2064694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the last modified file in a directory in Java?
提问by jumar
How do I find the last modified file in a directory in java?
如何在java中的目录中找到最后修改的文件?
采纳答案by Bozho
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;
}
回答by matt b
Combine these two:
结合这两个:
- You can get the last modified time of a File using
File.lastModified()
. - To list all of the files in a directory, use
File.listFiles()
.
- 您可以使用
File.lastModified()
. - 要列出目录中的所有文件,请使用
File.listFiles()
.
Note that in Java the java.io.File
object is used for both directories and files.
请注意,在 Java 中,java.io.File
对象用于目录和文件。
回答by Emil H
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.
您可以使用 File.lastModified() 方法检索上次修改的时间。我建议的解决方案是实现一个按 lastModified() 顺序排序的自定义比较器,并将目录中的所有文件插入到使用此比较器排序的 TreeSet 中。
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.
如果您只需要最后一个文件,Bozho 建议的解决方案可能会更快。另一方面,如果您需要做一些更复杂的事情,这可能很有用。
回答by Vinodh Ramasubramanian
The comparator in Emil's solution would be cleaner this way
这样 Emil 解决方案中的比较器会更干净
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.
投射(a.lastModified() - b.lastModified())
到int
可能会产生意想不到的结果。
回答by rahulmohan
Your problem is similar to: How to get only 10 last modified files from directory using Java?
您的问题类似于:如何使用 Java 从目录中仅获取 10 个最后修改的文件?
Just change the filter code to have only one File and the accept method should simply compare the two time stamps.
只需将过滤器代码更改为只有一个 File,accept 方法应该简单地比较两个时间戳。
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.
现在,使用此过滤器的实例作为参数调用 dir.listFiles。最后,filter.topFile 是最后修改的文件。
回答by John Jintire
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
这对我很有用
回答by Praneeth
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());
}
}
回答by MarcosNC
Let's assume that the variable thePath
contains the directory we want to search, the following snippet returns the last modified file inside it:
假设变量thePath
包含我们要搜索的目录,以下代码段返回其中最后修改的文件:
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).
- 首先按文件的最后修改时间反向排序,
- 然后跳过目录本身,
- 最后取流中的第一个元素(这是最后修改的元素)。
回答by Bax
Java 8
爪哇 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);
}
}