Java - get the newest file in a directory?

后端 未结 9 1384
难免孤独
难免孤独 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;
    }
    

提交回复
热议问题