You can use a wildcardard using a PathMatcher:
You can use a Pattern like this one for your PathMatcher:
/* Find test.zip in any subfolder inside 'origin + folderNames.get(i)'
* If origin + folderNames.get(i) is \test\orig\test_1
* The pattern will match:
* \test\orig\test_1\randomfolder\test.zip
* But won't match (Use ** instead of * to match these Paths):
* \test\orig\test_1\randomfolder\anotherRandomFolder\test.zip
* \test\orig\test_1\test.zip
*/
String pattern = origin + folderNames.get(i) + "/*/test.zip";
There are details about the syntax of this pattern in the FileSysten.getPathMather method. The code to create the PathMather could be:
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
You can find all the files that match this pattern using Files.find()
method:
Stream<Path> paths = Files.find(basePath, Integer.MAX_VALUE, (path, f)->pathMatcher.matches(path));
The find method returns a Stream<Path>
. You can do your operation on that Stream or convert it to a List.
paths.forEach(...);
Or:
List<Path> pathsList = paths.collect(Collectors.toList());
Path path = FileSystems.getDefault().getPath(origin + folderNames.get(i)); DirectoryStream<Path> stream = Files.newDirectoryStream(path, "/*/test.zip"); File input = new File(stream);
Since stream is not a String i cant get the file to work. – MucorPath
from the stream. And from thePath
you can retrieve theFile
usingtoFile()
. Docs are your friend. – Swagsman