I am trying to match file paths of the following pattern:
/Users/someuser/folder/folder/config/server1/overlay.properties
I am using the following code to walk through the files in a path and match files of the above pattern:
String SOURCE_CONFIG_PATH = "/Users/someuser/folder/folder/config";
Files.walk(Paths.get(SOURCE_CONFIG_PATH))
.filter(Files::isRegularFile)
.filter(file -> file.getFileName().toString().matches(".*/overlay\\.properties$"))
.forEach(file -> {System.out.println(file.toString());});
This does not match the files, but the following code does:
filter(file -> file.getFileName().toString().matches(".*overlay\\.properties$"))
which would also pick /Users/someuser/folder/folder/config/server1/shouldnotmatchoverlay.properties
Have tried escaping /
resulting in ".*\\/overlay\\.properties$"
and ".*\\\\/overlay\\.properties$"
which has not solved the issue.
The getFileName()
method, rather unsurprisingly, returns only the file name, not the complete path. As defined by the Javadoc:
The file name is the farthest element from the root in the directory hierarchy.
For the given path of /Users/someuser/folder/folder/config/server1/overlay.properties
, the file name is overlay.properties
. If you just need to match files with that file name, regardless of their path, you don't need any regular expressions and can just use equals()
:
filter(file -> file.getFileName().toString().equals("overlay.properties"))