我编写了一个程序,通过传递其扩展名来查找指定类型的所有文件。我的问题是,程序仅在 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();
}
}