0

我正在尝试制作一个遍历具有指定扩展名的目录和子目录的程序。这是我到目前为止的代码。我正在尝试使用endsWith方法但是因为我传递文件类型的参数进行递归调用,我不能使用增强的 For 循环中的字符串。

import java.io.File;

公共类 Traverse_Recursively {

/**
 * @param args
 */
public static void main(String[] args) {
    File inputFolder = new File("c:/inputFolder");
    traverse(inputFolder, "");
}

public static void traverse(File parentNode, String leftIndent) {
    if (parentNode.isDirectory()) {
        System.out.println(leftIndent + parentNode.getName());

        leftIndent += "     ";

        File childNodes[] = parentNode.listFiles();
        for (File childNode : childNodes) {
            traverse(childNode, leftIndent);
        }
    } else {

        System.out.println(leftIndent +"|   --> "+ parentNode.getName());

    }
}

}

4

2 回答 2

1

You could use the Java 7 Files.walkFileTree method - it'll make things much easier I think:

    Path path = Paths.get(<your root directory>);
    Files.walkFileTree(path, new FileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("visitFile: " + file.getFileName());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            System.out.println("postVisitDirectory: " + dir.getFileName());
            return FileVisitResult.CONTINUE;
        }
    });

If you're only interested in files, you only need to do something in the visitFile method.

于 2013-02-17T09:24:51.287 回答
0

如果您使用的是 java 6 或更早版本,则可以为此目的使用 apache commons FileUtils 或 DirectoryWalker。

于 2013-02-17T10:37:18.957 回答