以递归方式显示根文件夹下的所有文件和每个文件的目录

时间:2011-09-27 12:07:39

标签: java

我希望以递归方式显示根目录下的每个文件和每个文件的目录

输出应该如下所示

filename --->包含该文件的目录

例如,

filename.jpg ---&以及c:\工作区

filename.jpg位于c:\ workspace,即:路径为c:\ workspace \ filename.txt每个目录中有许多文件

2 个答案:

答案 0 :(得分:4)

请记住,此解决方案中将覆盖具有相同名称的文件名(您需要Map<String, List<File>>才能允许此操作):

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

    Map<String, File> map = getFiles(new File("."));

    for (String name : map.keySet())
        if (name.endsWith(".txt")) // display filter
            System.out.println(name + " ---> " + map.get(name));
}

private static Map<String, File> getFiles(File current) {

    Map<String, File> map = new HashMap<String, File>();

    if (current.isDirectory()) { 
        for (File file : current.listFiles()) {
            map.put(file.getName(), current);
            map.putAll(getFiles(file));
        }
    }

    return map;
}

示例输出:

test1.txt ---> .
test2.txt ---> .\doc
test3.txt ---> .\doc\test

答案 1 :(得分:0)

您可以使用Apache Commons Fileutils

public static void main(String[] args) throws IOException {
    File rootDir = new File("/home/marco/tmp/");
    Collection<File> files = FileUtils.listFiles(rootDir, new String[] {
            "jpeg", "log" }, true);
    for (File file : files) {
        String path = file.getAbsolutePath();
        System.out.println(file.getName() + " -> "
                + path.substring(0, path.lastIndexOf('/')));
    }
}

listFiles的第一个参数是您要从中开始搜索的目录,第二个参数是String的数组,提供所需的文件扩展名,第三个参数是{{如果搜索是递归的话,请说明。

示例输出:

boolean
相关问题