Java - 获取目录中的最新文件?

时间:2008-11-13 00:46:06

标签: java file-io filesystems

是否有人有一个Java片段可以返回目录中的最新文件(或者是一个简化这种事情的库的知识)?

9 个答案:

答案 0 :(得分:56)

返回上次修改时间:

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;
}

答案 1 :(得分:26)

在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
}     

答案 2 :(得分:16)

这对我来说非常好:

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;
}

答案 3 :(得分:1)

类似的东西:

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 ));
    }
}

答案 4 :(得分:1)

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;
}

答案 5 :(得分:1)

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;
}

答案 6 :(得分:0)

这是对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;
}

答案 7 :(得分:0)

这将返回最新创建的文件,我这样做是因为在某些情况下创建文件时,它不一定总是具有正确的修改日期。

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;
}

答案 8 :(得分:0)

此代码对我来说很有效:

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