1

I have the following code which works fine under Linux/Unix:

Files.walk(Paths.get(getStartingPath()))
     .filter(Files::isDirectory)
     // Skip directories which start with a dot (like, for example: .index)
     .filter(path -> !path.toAbsolutePath().toString().matches(".*/\\..*"))
     // Note: Sorting can be expensive:
     .sorted()
     .forEach(operation::execute);

However, under Windows, this part seems to not work properly:

     .filter(path -> !path.toAbsolutePath().toString().matches(".*/\\..*"))

What would be the proper way to make this OS-independent?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
carlspring
  • 31,231
  • 29
  • 115
  • 197

2 Answers2

3

You should not match the Path against hard-coded file separators. This is bound to cause problems.

What you want here is a way to get the name of the directory and skip it if it starts with a dot. You can retrieve the name of the directory with getFileName():

Returns the name of the file or directory denoted by this path as a Path object. The file name is the farthest element from the root in the directory hierarchy.

Then you can use startsWith(".") to see if it starts with a dot or not.

As such, you could have

.filter(path -> !path.getFileName().startsWith("."))
Tunaki
  • 132,869
  • 46
  • 340
  • 423
2

Another solution to what @Tunaki suggests is to try replacing the forward slash with the OS-specific file separator (you will need to escape it in case it is the backslash character on Windows):

.filter(path -> 
        !path.toAbsolutePath().toString().matches(".*"
                                        + Pattern.quote(File.separator) + "\\..*"))
M A
  • 71,713
  • 13
  • 134
  • 174