Java Path File List nio listDirsRecursive(String pathStr, String pattern, int maxDepth)

Here you can find the source of listDirsRecursive(String pathStr, String pattern, int maxDepth)

Description

list Dirs Recursive

License

BSD License

Declaration

public static String[] listDirsRecursive(String pathStr, String pattern, int maxDepth) 

Method Source Code


//package com.java2s;
//License from project: BSD License 

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static String[] listDirsRecursive(String pathStr, String pattern, int maxDepth) {
        ///*  w  ww  .  java 2 s. com*/
        final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(pattern);
        Path path = Paths.get(pathStr);
        final List<String> files = new ArrayList<>();
        if (maxDepth == -1) {
            maxDepth = Integer.MAX_VALUE;
        }
        try {
            Files.walkFileTree(path, Collections.<FileVisitOption>emptySet(), maxDepth,
                    new SimpleFileVisitor<Path>() {
                        @Override
                        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                                throws IOException {
                            if (matcher.matches(dir)) {
                                files.add(dir.toString());
                            }
                            return FileVisitResult.CONTINUE;
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return files.toArray(new String[files.size()]);
    }
}

Related

  1. listChildren(Path dir)
  2. listChildren(Path dir, boolean searchDirectory)
  3. listChildren(Path directory)
  4. listChildren(Path directory)
  5. listDir(Path dir)
  6. listFiles(final Path path)
  7. listFiles(Path base, StringBuilder b)
  8. listFiles(Path basePath)
  9. listFiles(Path dir)