我已經編寫了一個程序,通過傳遞其擴展名來查找指定類型的所有文件。 我的問題是,程序僅在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();
}
}
「C drive only」和「whole hard disk」有什麼區別? – 2013-07-26 06:20:49
在main方法中調用usage()後不應該有「return」語句嗎? – Henrik
我已經使用了退出功能 – Vicky