0

I need to load all files that matches the path or regular expression.

If the path is

"C:\Users\me\Desktop\project\src\test\resources\screenshots/*/*.png"

it should find all screenshots in "screenshots" folder. If the path is

C:\Users\me\Desktop\project\src\test\resources\screenshots/first.png

it should find only the one file.

I was trying to list all files that match the criteria using:

File dir = new File("/");
FileFilter fileFilter = new WildcardFileFilter(absolutePath);
File[] files = dir.listFiles(fileFilter);

but this is not recursive and finds files only in home folder.

I tried to also use Spring way:

ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
return resolver.getResources(pattern);

But this expects only relative paths and looking for files in classpath.

What is the correct, standard and pretty way how to do this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Johnyb
  • 980
  • 1
  • 12
  • 27
  • @SimonMartinelli no, there is nothing about regexps in there.. – Johnyb Aug 16 '21 at 14:21
  • 1
    Sure it is! Files.walk gives you a stream of files and then you can filter howerver you like Files.walk(Paths.get(path)).filter() – Simon Martinelli Aug 16 '21 at 14:24
  • @SimonMartinelli Files.walk however ends when there is an exception, like AccessDenied. Isnt it also super non efficent? It seems it just literally traverse everything – Johnyb Aug 16 '21 at 14:31
  • https://stackoverflow.com/questions/66542005/files-walkfiletree-vs-files-walk-performance-on-windows-ntfs – Simon Martinelli Aug 16 '21 at 14:34
  • @SimonMartinelli there is still problem with access denied exception if it meets some folder it has no access to – Johnyb Aug 16 '21 at 15:45

1 Answers1

-1
Files.walk(Paths.get(path))
   .filter(Files::isRegularFile)
   .filter(p ->p.toString().matches(".*\\.png$"))
   .forEach(System.out::println);

Passing your screenshots folder path as a String ('path') to the above will filter for you

g00se
  • 3,207
  • 2
  • 5
  • 9
  • this still throws AccessDenied exception if there is some folder it does not have access to on the way. + the regexp can be present anywhere in the path,.. – Johnyb Aug 16 '21 at 15:45
  • Not sure if that's filterable. Shall check – though it begs the question: "Why, in your own screenshots tree, would there be files to which you don't have access?" – g00se Aug 16 '21 at 15:55
  • that tree was just an example, the path can be literally anything user wants it to be – Johnyb Aug 17 '21 at 09:19
  • You need to go for the 'long version' of recursing the fs to be able to cope with errors probably – g00se Aug 17 '21 at 15:11