[Java] 디렉토리에 있는 파일목록 추출하기

Study/Java 2019. 12. 20. 21:07 Posted by meanoflife
반응형


디렉토리에 있는 파일목록 추출하기


파일 단위로 업무를 처리하기 위해 특정 '디렉토리'안에 있는 파일목록을 추출합니다.
추출된 목록을 이용하여 파일을 핸들링할 수 있습니다.

※ SOURCE

    public static void main(String[] args) { 
         
        String strDirPath = "C:\\workspace\\Test\\"; 
         
        File path = new File( strDirPath ); 
        File[] fList = path.listFiles(); 
         
        for( int i = 0; i < fList.length; i++ ) { 
             
            if( fList[i].isFile() ) { 
                System.out.println( "[파일] " + fList[i].getPath() );  // 파일의 FullPath 출력 
            } 
            else if( fList[i].isDirectory() ) { 
                System.out.println( "[폴더] " + fList[i].getPath() );  // 재귀함수 호출 
            } 
        } 
    } 


* RESULT

    [파일] A.txt : C:\workspace\Test\A.txt 
    [파일] B.txt : C:\workspace\Test\B.txt 
    [파일] C.txt : C:\workspace\Test\C.txt 
    [폴더] Sub1 : C:\workspace\Test\Sub1 
    [폴더] Sub2 : C:\workspace\Test\Sub2 



※ 참고

 

    - File.getName() : 파일객체의 이름, 파일명을 가져온다. ( Ex.A.txt )
    - File.getPath() : 파일객체의 전체경로를 가져온다.( Ex.C:\workspace\Test\A.txt )

    - File.isFile() : 파일객체의 유형이 '파일'인지 체크. ( return true/false )
    - File.isDirectory() : 파일객체의 유형이 '디렉토리'인지 체크. ( return true/false )

끝.

반응형