How do I find the last modified file in a directory with java? get file name of last file modified java EXP: i have: test_4755_err.log. test_4588_err.log. test_14587_err.log.` i wanna get thé last file between this files
Asked
Active
Viewed 55 times
-4
-
Can you at least capitalize your sentences? – Anubian Noob May 16 '14 at 16:13
-
what about scan all files and check? – Marco Acierno May 16 '14 at 16:14
-
1When posting on stackoverflow for a question like this, you need to show what you have currently tried, and why it does not presently work. If you have already attempted to solve the problem, please go ahead and post your current solution. – Paul Richter May 16 '14 at 16:15
-
check out this link if it helps - http://stackoverflow.com/questions/18803675/get-last-modified-date-of-files-in-a-directory – Ronn Wilder May 16 '14 at 16:23
-
Files.getLastModifiedTime(directory) should work for directory too – Marco Acierno May 16 '14 at 16:33
-
@PaulRichter I tried but i don't have result if you want i send you my code Thanks! – user3505854 May 18 '14 at 13:03
1 Answers
0
Are you just looking for the file that was last modified? You could do:
File lastModified = null;
String directory = "."; // replace with your directory
File[] files = new File(directory).listFiles();
if(files != null){
Arrays.sort(files, new Comparator<File>(){
@Override
public int compare(File o, File t){
// reverse the ordering so the newest file is first in the array
return -1 * Long.compare(o.lastModified(), t.lastModified());
}
});
lastModified = files[0];
}
As pointed out, this would be more efficient:
File newest = null
for(File f : new File(dir).listFiles()){
if(newest == null || f.lastModified() > newest.lastModified()){
newest = f;
}
}

Ryan S
- 370
- 2
- 12
-
1If you're just looking for the newest file or the oldest file, it's wasteful to bring all of them into an array and sort them. You could just iterate over the files and keep the newest-so-far. Iterating over the files is O(n), while sorting them is O(nlogn). – Kenster May 16 '14 at 16:23