ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 재귀호출의 예 : 파일,디렉토리 트리구조 출력
    개발 정보/JAVA 2017. 8. 3. 02:01

    - 파일 클래스로 특정 디렉토리 초기값 지정

    - 리스트에 파일 형태의 구조로 담아 출력해 줌 (리스트에 map형태로 변경할 수도 있음. 가독성이 높아지겠지)

    - 이 코드를 응용하면, DB에 내 PC의 파일,디렉토리 정보를 저장해놓고 웹에서 파일을 업로드하거나, 저장 가능

      (파일이 엄청 많은 경우는 어쩌지?)

      - 필드 정보

         1) 구분코드 : FILE인지, 디렉토리인지

         2) 파일 혹은 폴더명

         3) 파일 혹은 폴더 경로

         4) 파일 크기

         5) 파일 확장자

         6) 파일 내용 (텍스트 파일은 가능하나, 나머지는 파일 필터링 툴 필요할 듯)


    * 이 코드가 어디에 쓰이면 쓸모가 있을까?

       - 웹에서 파일 업로드 및 저장 기능은 아무짝에도 쓸모 없어 보인다는... 이미 제공하는 라이브러리 들이 많거든...

       - 재귀호출의 활용 예를 찾는게 더 의미가 있을 듯... ㅠ_ㅠ

       - 생각해보자... 님들 아이디어 있음 댓글로 의견 주시면 감사하겠씁니다^^

    * 이 외 재귀호출의 예로 팩토리얼(순열), 하노이의 탑 등 포스팅 예정~


    <소스 코드>

    import java.io.File;

    import java.io.IOException;

    import java.util.ArrayList;

    /**

     * 파일/디렉토리 구조 출력

     * @author KKC

     *

     */

    public class IoTest_02 {

    public static void main(String[] args) {

    File f = new File("A:\\Study");

    ArrayList<File> subFiles = new ArrayList<File>();

    if(!f.exists()) {

    System.out.println("디렉토리가 존재하지 않습니다.");

    }

    findSubFiles(f, subFiles);

    System.out.println("---------------------------");

    for (File file : subFiles) {

    if(file.isFile()) {

    System.out.println("파일 이름: "+file.getName());

    try {

    System.out.println("파일경로: "+file.getCanonicalPath());

    } catch (Exception e) {

    e.printStackTrace();

    }

    System.out.println("파일크기: "+file.length());

    System.out.println("---------------------------");

    }

    else if (file.isDirectory()) {

    System.out.println("디렉토리 이름: "+file.getName());

    try {

    System.out.println("디렉토리경로: "+file.getCanonicalPath());

    } catch (IOException e) {

    e.printStackTrace();

    }

    System.out.println("---------------------------");

    }

    }

    }

    public static void findSubFiles(File parentFile, ArrayList<File> subFiles) {

    if(parentFile.isFile()){

    subFiles.add(parentFile);

    } else if(parentFile.isDirectory()) {

    subFiles.add(parentFile);

    File[] childFiles = parentFile.listFiles();

    for (File childFile : childFiles) {

    findSubFiles(childFile, subFiles);

    }

    }

    }

    }


Designed by Tistory.