본문 바로가기

Programming/JAVA

디렉토리 하위 탐색 하기

디렉토리를 인자로 주면 해당 폴더 아래의 모든 디렉토리와 파일을 뒤지는 visitAllDirsAndFiles 메소드와 디렉토리만 뒤지는 visitAllDirs 메소드를 소개 합니다.

visitAllDirsAndFiles 메소드는 기술한 폴더의 모든 디렉토리와 파일을 탐색하는데 process 메소드는 적당히 필요에 따라 만들어 쓰시면 되구여, 예를들면 디렉톨리 이름을 출력 한다든지...

예제를 참고 하세요~

    // Process all files and directories under dir
    public static void visitAllDirsAndFiles(File dir) {

        // You can do whatever you want with this directory
        // E.g. printing its name to the console
        process(dir);
   
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirsAndFiles(new File(dir, children[i]));
            }
        }
    }
   
    // Process only directories under dir
    public static void visitAllDirs(File dir) {
        if (dir.isDirectory()) {
     
            // You can do whatever you want with this directory
            // E.g. printing its name to the console
            process(dir);
   
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirs(new File(dir, children[i]));
            }
        }
    }