개인참고자료/자바(네트워크)

바이트 기반 스트림 - File 클래스를 이용한 디렉토리의 파일 목록 출력

경진 2008. 7. 13. 11:15
File 클래스를 이용한 디렉토리의 파일 목록 출력 

File 클래스를 이용해서 디렉토리 안의 파일 목록을 출력하는 예제다. 디렉토리 일 경우에는 디렉토리라고 출력하며, 디렉토리가 아닐 경우에는 '파일'이라고 출력한다. 또한 파일의 경우에는 파일 용량도 출력한다.

import java.io.*;

public class FileList {

    public static void main(String[] args) {
        if(args.length != 1){
            System.out.println("사용법 : java FileList 디렉토리이름");
            System.exit(0);
        } // if end       

        File f = new File(args[0]);
        if(!f.exists()){ // 파일의 존재 여부
            System.out.println("디렉토리가 존재하지 않습니다.");
            System.exit(0);
        } // if end 

        if(f.isDirectory()){ // 사용자가 입력한 인자값이 파일과 디렉토리를 구분한다.
            File[] fileList = f.listFiles(); // listFiles() 메소드를 사용해 파일목록을 배열 형태로 반환한다.
            for(int i = 0; i < fileList.length; i++){ // fileList(파일목록)의 배열의 개수만큼 반복한다.
                System.out.print(fileList[i].getName()); // 파일목록에 있는 배열의 이름을 가져온다.
                System.out.print("\t");
                if(fileList[i].isDirectory()) // 파일목록이 파일인지 디렉토리인지 구분한다.
                    System.out.println("디렉토리");
                else{
                    System.out.print("파일");
                    System.out.print("\t");
                    System.out.println(fileList[i].length()); // 파일 크기를 출력한다.
                } // if end 
            } // for end 
        }else{
            System.out.println("디렉토리가 아닙니다.");
        } // if end 
    } // main end 
}

결과화면