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