Java - get the newest file in a directory?

后端 未结 9 1396
难免孤独
难免孤独 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: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
    

提交回复
热议问题