我是java中的小白。我有自己的努力来完成这些事情。但我当然面临挑战。我有一个虚拟程序,用于搜索作为命令行参数提供的特定扩展名(.txt)的文件。我正在尝试制作这些搜索文件的文件对象以进行进一步操作。但我无法理解如何在我的代码中执行此操作.. 这是我的代码示例...
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);
}
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;
}
}
public static void main(String[] args) throws IOException {
Iterable<Path> root;
root = FileSystems.getDefault().getRootDirectories();
// System.out.println(name.getAbsolutePath());
for (Path startingDir : FileSystems.getDefault().getRootDirectories()) {
String pattern = args[0];
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
}
}
}