简体   繁体   中英

In java, list all files recursively. but skip one sub-directory

I am listing all the files names in a given directory( recursively). That includes showing the file names in sub-directories also. How I can restrict it to not to show the files/dir under one specific sub-directory (skip one specific directory)

    File file = new File(FILE_PATH);
    // Recursively search for all the resource files.
    Collection files = FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
    for (Iterator iterator = files.iterator(); iterator.hasNext();)
    {
        File fileIter = (File) iterator.next();
        System.out.println("File = " + fileIter.getPath());

    }

Java SE has its own method for doing this: Files.walkFileTree . You pass it a FileVisitor (usually a subclass of SimpleFileVisitor), each of whose methods can return a FileVisitResult . To skip a directory, simply return FileVisitResult.SKIP_SUBTREE:

Files.walkFileTree(file.toPath(),
    new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir,
                                                 BasicFileAttributes attr)
        throws IOException {
            if (dir.endsWith("forbiddenDir")) {
                return FileVisitResult.SKIP_SUBTREE;
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file,
                                         BasicFileAttributes attr)
        throws IOException {
            System.out.println("File = " + file);
            return FileVisitResult.CONTINUE;
        }
    });

The Path class is the modern replacement for the obsolete File class. You should avoid using File, since many of its methods do not report errors properly. If you absolutely need a File object, Path has a toFile() method. Conversely, File has a toPath() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM