web-dev-qa-db-fra.com

Java - récupère le fichier le plus récent dans un répertoire?

Quelqu'un a-t-il un fragment de code Java capable de renvoyer le fichier le plus récent dans un répertoire (ou la connaissance d'une bibliothèque simplifiant ce type de choses)?

36
tpark

Ceci retourne la dernière modification:

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;
}
52
José Leal

En 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
}     
24
Almaz

Cela fonctionne parfaitement bien pour moi:

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;
}
15
John Jintire
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;
}
1
Tested
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;
}
1
Prasanth V

Voici une petite modification au code de Jose qui garantit que le dossier contient au moins 1 fichier. Le travail est génial dans mon application!

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

Quelque chose comme:

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