Java - 获取目录中的最新文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/285955/
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
Java - get the newest file in a directory?
提问by
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)?
是否有人拥有可以返回目录中最新文件的 Java 片段(或了解简化此类事情的库)?
回答by OscarRyz
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 ));
}
}
回答by José Leal
The following code returns the last modified file or folder:
以下代码返回最后修改的文件或文件夹:
public static File getLastModified(String directoryFilePath)
{
File directory = new File(directoryFilePath);
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
}
}
}
return chosenFile;
}
Note that it required Java 8
or newer due to the lambda expression.
请注意,Java 8
由于 lambda 表达式,它需要或更新。
回答by John Jintire
This works perfectly fine for me:
这对我来说非常好:
import org.apache.commons.io.FileUtils;
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;
}
回答by Almaz
In Java 8:
在 Java 8 中:
Path dir = Paths.get("./path/somewhere"); // specify your directory
Optional<Path> lastFilePath = Files.list(dir) // here we get the stream with full directory listing
.filter(f -> !Files.isDirectory(f)) // exclude subdirectories from listing
.max(Comparator.comparingLong(f -> f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field
if ( lastFilePath.isPresent() ) // your folder may be empty
{
// do your code here, lastFilePath contains all you need
}
回答by Prasanth V
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 Tested
public File getLastDownloadedFile() {
File choice = null;
try {
File fl = new File("C:/Users/" + System.getProperty("user.name")
+ "/Downloads/");
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
//Sleep to download file if not required can be removed
Thread.sleep(30000);
long lastMod = Long.MIN_VALUE;
for (File file : files) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
} catch (Exception e) {
System.out.println("Exception while getting the last download file :"
+ e.getMessage());
}
System.out.println("The last downloaded file is " + choice.getPath());
System.out.println("The last downloaded file is " + choice.getPath(),true);
return choice;
}
回答by Asheron
Here's a small modification to Jose's code which makes sure the folder has at least 1 file in it. Work's great in my app!
这是对 Jose 代码的一个小修改,它确保文件夹中至少有 1 个文件。在我的应用程序中工作很棒!
public static File lastFileModified(String dir) {
File fl = new File(dir);
File choice = null;
if (fl.listFiles().length>0) {
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
long lastMod = Long.MIN_VALUE;
for (File file : files) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
}
return choice;
}
回答by theeman05
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;
}
回答by SaurabhGuptaAricent
This code works for me well:
这段代码对我很有效:
public String pickLatestFileFromDownloads() {
String currentUsersHomeDir = System.getProperty("user.home");
String downloadFolder = currentUsersHomeDir + File.separator + "Downloads" + File.separator;
File dir = new File(downloadFolder);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
testLogger.info("There is no file in the folder");
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
String k = lastModifiedFile.toString();
System.out.println(lastModifiedFile);
Path p = Paths.get(k);
String file = p.getFileName().toString();
return file;
}
//PostedBy: saurabh Gupta Aricent-provar