Java - get the newest file in a directory?

后端 未结 9 1356
难免孤独
难免孤独 2020-12-01 02:13

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)?

相关标签:
9条回答
  • 2020-12-01 02:20
    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;
    }
    
    0 讨论(0)
  • 2020-12-01 02:28

    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
    
    0 讨论(0)
  • 2020-12-01 02:29

    In 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
    }     
    
    0 讨论(0)
  • 2020-12-01 02:30

    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.

    0 讨论(0)
  • 2020-12-01 02:30

    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!

    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 讨论(0)
  • 2020-12-01 02:34

    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;
    }
    
    0 讨论(0)
提交回复
热议问题