Allow wildcards to search for subdirectories from

2019-09-21 16:34发布

问题:

This question already has an answer here:

  • How to search for a subdirectory from a parent directory? [closed] 2 answers
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

public class DirectoryContents {

    public static void main(String[] args) throws IOException {

        File f = new File("."); 
        FileFilter directoryFilter = new FileFilter() {
            public boolean accept(File file) {
            return file.isDirectory();
            }
        };

        File[] files = f.listFiles(directoryFilter);
        for (File file : files) {
            if (file.isDirectory())
                System.out.print("directory:"); 
            else
                System.out.print("     file:");

            System.out.println(file.getCanonicalPath());
        }
    }
}

I m able to list all the sub directories from the parent directory. But I would like to search for particular sub directory in java.Is there any way?

directory:C:\projects\workspace\testing

how to list only subdirectories (z1) and not files? (Sub directory z1 is present in various sub directories)

directory:C:\projects\workspace\testing\z1
directory:C:\projects\workspace\testing\f5\z1
directory:C:\projects\workspace\testing\f5\a\g\h\d

The Output should be directories containing z1

回答1:

Java 7 made this type of thing easy with lots of flexibility. I would use a Java 7 PathMatcher with a glob pattern (or a regex pattern if the sophistication is needed) and use it in a FileVistor. Then just walk the file tree via Files.walkFileTree().

import java.io.IOException;
import java.nio.file.FileSystems;
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;

public class StackOverflow20443793
{
    //Our FileVisitor Implementation. We extend SimpleFileVisitor to save work
    protected class Finder extends SimpleFileVisitor<Path>
    {
        private final PathMatcher matcher;

        Finder(String pattern)
        {
            matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
        }

        void find(Path path)
        {
            Path name = path.getFileName();
            if ((name != null) && matcher.matches(name))
            {
                processDirectory(path);
            }
        }


        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException
        {
            //Since we only care about directories, we only override 
            // the preVisitDirectory method. The super does null checks for us
            super.preVisitDirectory(dir, attrs);
            find(dir);
            return FileVisitResult.CONTINUE;
        }
    }


    private void findAndProcessSubDirectories(Path startingDirectory, String pattern) throws IOException
    {
        Finder finder = new Finder(pattern);
        Files.walkFileTree(startingDirectory, finder);
    }

    private void processDirectory(Path dir)
    {
        System.out.println(dir);
    }

    public static void main(String... args) throws Exception
    {
        StackOverflow20443793 runner = new StackOverflow20443793();
        //Find all directories in path named "z1"
        runner.findAndProcessSubDirectories(Paths.get("P:\\tmp\\findExample"), "z1");
        System.out.println("=====");
        //Find all directories in path named "z*"
        runner.findAndProcessSubDirectories(Paths.get("P:\\tmp\\findExample"), "z*");

        System.exit(0);
    }
}

Output:

    C:\projects\workspace\testing\f5\a\g\h\d\z1
    C:\projects\workspace\testing\f5\z1
    C:\projects\workspace\testing\z1
    =====
    C:\projects\workspace\testing\f5\a\g\h\d\z1
    C:\projects\workspace\testing\f5\z1
    C:\projects\workspace\testing\z1
    C:\projects\workspace\testing\z2

For more info and examples, see http://docs.oracle.com/javase/tutorial/essential/io/find.html and the JavaDocs I linked.



回答2:

Two things:

  1. The easiest way to search through subdirectories is by recursion.
  2. You need to check the filename, before printing. You can do this with regular expressions using ".*z1.*

So in total something like this

private static final FileFilter directoryFilter = new FileFilter() {
  public boolean accept(File file) {
    return file.isDirectory();
  }
};

private static void printDirectories(File dir, string pattern) {
  // Print this directory if it matches the pattern
  if (dir.getName().matches(pattern)) {
    System.out.println(dir.getAbsolutePath());
  }
  // Search all sub directories
  for (String string : f.listFiles(directoryFilter)) {
    printDirectories(subDir);
  }
}

public static void main(String[] args) {
  printDirectories(new File("."), ".*z1.*");
}