Search code examples
javadir

Get the highest numeric file name(as int) from directory - Java


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?


Solution

  • You can use Java 7 NIO's DirectoryStream to go through your files using a filter to make sure you ignore the files that are not relevant to you.

    Here is the filter:

    class NumericFilter implements DirectoryStream.Filter<Path> {
    
        private static final Pattern PATTERN = Pattern.compile("\\d+|\\d+\\..*");
    
        @Override
        public boolean accept(Path entry) throws IOException {
            return PATTERN.matcher(entry.getFileName().toString()).matches();
        }
    
    }
    

    And here is the code using it:

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(dir), new NumericFilter())) {
        for (Path path : stream) {
            // do what you want
        }
    }
    

    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:

    final Pattern pattern = Pattern.compile("\\d+\\..*");
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(dir),
            entry -> pattern.matcher(entry.getFileName().toString()).matches())) {
        for (Path path : stream) {
            // do what you want
        }
    }