开发者

display all the files and the directory of the each file under a root folder recursively

i want to display all the files and the directory of each file under a root directory recursively

the output should look like this

filename ---> the directory which contains that file

for example filename.jpg--->c:\workspace

t开发者_运维问答he filename.jpg is in c:\workspace i.e :the path is c:\workspace\filename.txt there are many files in each directory


Remember that filenames with the same name will be overridden in this solution (you need a Map<String, List<File>> to allow this):

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;
}

Example output:

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


You can use 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('/')));
    }
}

The first argument of listFiles is the directory from which you want to start searching, the second argument is an array of Strings giving the desired file extensions, and the third argument is a boolean saying if the search is recursive or not.

Example output:

visicheck.jpeg -> /home/marco/tmp
connettore.jpeg -> /home/marco/tmp
sme2.log -> /home/marco/tmp/sme2_v2_1/log
davmail_smtp.jpeg -> /home/marco/tmp
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜