简体   繁体   中英

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

the filename.jpg is in c:\\workspace ie :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 String s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM