Given a File dir I need to find the highest numeric file name(if any exist)
My approach:
// get the highest numeric file name(as int) from given directory
public static final int getHighestNumericFileName(File dir) {
int result = -1;
for (File f : dir.listFiles()) {
String name = f.getName();
name = name.substring(0, name.indexOf('.'));
if (StringUtils.isNumeric(name)) {
int val = Integer.parseInt(name);
if (val > result)
result = val;
}
}
return result;
}
Considering the file count in the folder can get quite large(300k+) my concern is performance related.
Is this at all an acceptable solution? And is there a better way?
You can use Java 7 NIO's
DirectoryStreamto go through your files using a filter to make sure you ignore the files that are not relevant to you.Here is the filter:
And here is the code using it:
This will only go through files with completely numeric names (without or with any extension).
Just for the record, here is a slightly simpler way to do the same with Java 8: