public Stream<Path> iterateFiles(Path path, String filePattern, boolean recursive) { PathMatcher matcher = FileSystems.getDefault().getPathMatcher(filePattern); return asStream(new FilesIterator(path, recursive)).filter(p -> matcher.matches(p)); } public Stream<Path> iterateFiles(Path path, String filePattern, String excludeFilePattern, boolean recursive) {
@Override public boolean hasNext() { if (iterator.hasNext()) return true; else if (recursive) { try { DirectoryStream<Path> dirs = Files.newDirectoryStream(currentPath); try { asStream(dirs.iterator()).filter(p -> p.toFile().isDirectory()).forEach(p -> stack.addLast(p)); } finally { dirs.close(); } } catch (IOException e) { throw new RuntimeException("Cannot read sub dirs", e); } while (!stack.isEmpty()) { initStream(stack.removeFirst()); if (iterator.hasNext()) return true; } } if (files != null) { try { files.close(); } catch (IOException e) { throw new RuntimeException("Cannot close files reader", e); } files = null; } return false; }
public FilesIterator(Path root, boolean recursive) { this.recursive = recursive; initStream(root); } private void initStream(Path path) {