有没有人有一个Java片段可以返回目录中的最新文件(或者是一个简化这种事情的库的知识)?
这将返回上次修改时间:
public static File lastFileModified(String dir) { File fl = new File(dir); File[] files = fl.listFiles(new FileFilter() { public boolean accept(File file) { return file.isFile(); } }); long lastMod = Long.MIN_VALUE; File choice = null; for (File file : files) { if (file.lastModified() > lastMod) { choice = file; lastMod = file.lastModified(); } } return choice; }
在Java 8中:
Path dir = Paths.get("./path/somewhere"); // specify your directory OptionallastFilePath = 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 }
这对我来说非常好:
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; }