How to retrieve a list of directories QUICKLY in Java?

后端 未结 14 934
轮回少年
轮回少年 2020-12-01 12:45

Suppose a very simple program that lists out all the subdirectories of a given directory. Sound simple enough? Except the only way to list all subdirectories in Java is to u

相关标签:
14条回答
  • 2020-12-01 13:08

    I don't know if the overhead of shelling out to cmd.exe would eat it up, but one possibility would be something like this:

    ...
    Runtime r = Runtime.getRuntime();
    Process p = r.exec("cmd.exe /k dir /s/b/ad C:\\folder");
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    for (;;) {
        String d = br.readLine();
        if (d == null)
            break;
        System.out.println(d);
    }
    ...
    
    • /s means search subdirectories
    • /ad means only return directories
    • /b means return the full pathname from the root
    0 讨论(0)
  • 2020-12-01 13:11

    Do you know the finite list of possible subdirectory names? If so, use a loop over all possible names and check for directory's existence.

    Otherwise, you can not get ONLY directory names in most underlying OSs (e.g. in Unix, the directory listing is merely reading contents of "directory" file, so there's no way to find "just directories" quickly without listing all the files).

    However, in NIO.2 in Java7 (see http://java.sun.com/developer/technicalArticles/javase/nio/#3 ), there's a way to have a streaming directory list so you don't get a full array of file elements cluttering your memory/network.

    0 讨论(0)
提交回复
热议问题