1. 재귀메소드 


- 자기자신을 호출하는 메소드


ex>재귀메소드를 사용해서 팩토리얼값 구하는 예제

package test01.file;

public class Test04_재귀메소드 {


    public static void main(String[] args){

        int n=4;

        //팩토리얼값 구해오기

        int num=fac(n);

        System.out.println(n+"!="+num);

    }

    public static int fac(int n){

        return (n>1)?n*fac(n-1):n;

    }

}

 

 





ex> c:\\java\\test 폴더를 삭제해 보세요.


package test01.file;

import java.io.File;

public class Quiz01 {


    public static void main(String[] args){


        File f=new File("c:\\java\\test");

        if(f.exists()){

            //test폴더안의 파일목록들 얻어오기

            File[] list=f.listFiles();

            for(File ff:list){

                if(ff.isFile()){

                    //디렉토리 안의 파일지우기

                    ff.delete();

                }

            }

            if(f.delete()){

                System.out.println("디렉토리 삭제 성공!");

            }

        }

    }

}

 

 



ex> c:\\java\\test 폴더를 삭제해 보세요. 

test폴더안에는 파일도 존재하고 디렉토리도 존재한다.

==>재귀메소드를 사용해 보세요.. 

package test01.file;

import java.io.File;


public class Quiz02 {


    public static void main(String[] args){


        File f=new File("c:\\java\\test");

        if(delDir(f)){

            System.out.println("디렉토리 삭제 성공");

        }else{

            System.out.println("디렉토리 삭제 실패");

        }

    }

    public static boolean delDir(File f){

        //디렉토리 안의 목록들 얻어오기

        File []list=f.listFiles();


        //디렉토리 안의 목록들을 삭제하기

        for(int i=0;i<list.length;i++){

            //목록이 파일이면

            if(list[i].isFile()){

                //파일삭제하기

                list[i].delete();

            }else{

                //목록이 디렉토리면

                //자신의메소드호출

                //(디렉토리안의목록들을삭제하기위해)

                delDir(list[i]);

            }

        }


        //자기자신의 폴더 삭제하기

        if(f.delete()){

            return true;

        }else{

            return false;

        }        

    }

}

 

 

 

 

 

ex>c:\\java\\test 폴더의 크기를 구해 보세요.

- 쉬운방법 : test폴더에 파일만 존재하는 경우

- 어려운방법 : 폴더안에 또 폴더가 존재하는 경우


package test01.file;

import java.io.File;


public class Quiz03 {

    public static void main(String[] args){

        File f=new File("c:\\java\\test");

        long size=getDirSize(f);

        System.out.println("디렉토리 크기:" + size +"bytes");

    }


    public static long getDirSize(File f){

        long fsize=0;

        File[] list=f.listFiles();

        for(int i=0;i<list.length;i++){

            if(list[i].isFile()){

                fsize+=list[i].length();

            }else{

                fsize+=getDirSize(list[i]);

            }

        }

        return fsize;

    }

}   

 

 



 

 

'JAVA' 카테고리의 다른 글

Network ( Ⅰ )  (0) 2014.09.12
스레드(Thread)  (0) 2014.09.12
File 클래스  (0) 2014.09.12
자바 IO ( Ⅱ )  (0) 2014.09.12
자바 IO - Stream ( Ⅰ )  (0) 2014.09.12

+ Recent posts