-1

拡張子を渡すことで、指定されたタイプのすべてのファイルを見つけるプログラムを作成しました。私の問題は、プログラムが C ドライブでのみファイルを検索していることですが、ハードディスク全体を検索したいのです。ここに私のプログラムサンプルがあります

public class Find {

public static class Finder extends SimpleFileVisitor<Path> {

    private final PathMatcher matcher;
    private int numMatches = 0;

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

    // Compares the glob pattern against
    // the file or directory name.
    void find(Path file) 
    {
        Path name = file.getFileName();
        if (name != null && matcher.matches(name)) 
        {
            numMatches++;
            System.out.println(file);
        }
    }

    // Prints the total number of
    // matches to standard out.
    void done() 
    {
        System.out.println("Matched: "+ numMatches);
    }

    // Invoke the pattern matching
    // method on each file.
    //@Override
    public FileVisitResult visitFile(Path file,BasicFileAttributes attrs) 
    {
        find(file);
        return CONTINUE;
    }

    // Invoke the pattern matching
    // method on each directory.
    //@Override
    public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs) 
    {
        find(dir);
        return CONTINUE;
    }

    //@Override
   public FileVisitResult visitFileFailed(Path file,IOException exc) 
    {
        System.err.println(exc);
        return CONTINUE;
    }
}

static void usage()
{
    System.err.println("java Find <path>" +" -name \"<glob_pattern>\"");
    System.exit(-1);
}

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

    if (args.length < 2 ) 
    {
        usage();
    } 
    Path startingDir = Paths.get(args[0]);
    String pattern = args[1];

    Finder finder = new Finder(pattern);
    Files.walkFileTree(startingDir, finder);
    finder.done();
}

}

4

2 に答える 2

2

このFile.listRoots()方法を使用して、Windows ですべてのドライブを見つけることができます。その後、各ドライブで独立した検索を行うだけです。

新しい API (java.nio.file) を使用する別の方法がありますFileSystem.getDefault().getRootDirectories()

for (Path startingDir : FileSystem.getDefault().getRootDirectories()) {
    // find files here
}
于 2013-07-26T06:21:33.530 に答える