경로 : C:\class\dev\eclipse
- 파일 : 11,598, 폴더 2,379
- 730MB (765,490,890 바이트)
String path = "C:\\class\\dev\\eclipse"; //몇 단계까지 자식폴더가 있는지 어떻게 앎?
File dir = new File(path); //-> 언제까지 내려가야할지 불특정한 상황
// -> 더이상 자식폴더가 없을때까지 무한 루프, 조건에 걸리면 break
int count = 0; //누적변수
if(dir.exists()) { //파일이 있으면
1. 목록 가져오기
File[] list = dir.listFiles(); //list배열에 dir(부모 폴더)의 파일들 값으로 넣기
2. 파일 개수 세기
//자식 파일 > 개수
for(File file : list) { //file에 list[] 복사
if(file.isFile()) { //파일만 고르기
count++; //파일이 있을때마다 count 1씩 증가
}
}
3. 자식 폴더 대상으로 방금 행동 반복
//자식 폴더 > 탐색 + 파일 개수
for(File subdir : list) { //subdir(자식폴더)에 list[] 복사
if(subdir.isDirectory()) { //폴더니?
//자식 폴더의 내용
File[] sublist = subdir.listFiles(); //sublist[]에 subdir(자식 폴더) 파일 복사
for(File subfile : sublist) { //subfile에 sublist[] 복사
if(subfile.isFile()) { //파일만 고르기
count++; //subfile 파일에 다가갈때마다 count 1씩 증가
}
}
//손자 폴더 > 탐색 + 파일 개수
for(File subsubdir : sublist) { //subsubdir에 sublist[] 복사
if(subsubdir.isDirectory()) { //subsubdir이 폴더니?
//손자 폴더의 내용
File[] subsublist = subsubdir.listFiles(); //subsublist[]에 subsubdir(손자 폴더) 파일 복사
for(File subsubfile : subsublist) { //subsubfile에 subsublist[] 파일 복사
count++; //subsubfile에 다가갈때마다 1씩 증가
}//for
}//if
}//for
}//if
} //for
System.out.printf("총 파일 개수: %,d개\n", count);
}
}
▼▼▼▼▼▼▼▼▼▼좀 더 가볍게▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
private int fileCount = 0; //메인에 공통으로 쓰일 수 있는 count변수 따로 빼기
private int dirCount = 0; //자식폴더 개수
private int length = 0; //파일 크기
경로: C:\class\dev\eclipse
- 파일 : 11,757, 폴더 2,501
- 730MB (765,853,013 바이트)
String path = "C:\\class\\dev\\eclipse";
File dir = new File(path);
if(dir.exists()) {
count(dir);
}
System.out.printf("총 파일 개수: %,d개\n", fileCount);
System.out.printf("총 폴더 개수: %,d개\n", dirCount);
System.out.printf("폴더 크기: %,dB\n", length);
System.out.printf("폴더 크기: %,dMB\n", length / 1024 / 1024);
}
private static void count(File dir) {
1. 목록 가져오기
File[] list = dir.listFiles(); //list[]에 dir에 있는 파일 넣기
2. 파일 개수 세기, 크기 세기
for(File file : list) { //file에 list[] 값 넣기
if(file.isFile()) { //file이 file이면
fileCount++; //file 개수세기
length += file.length(); //length변수에 file 크기 누적
}
}
3. 자식 폴더 대상으로 방금 행동 반복
자식 폴더가 없을때까지 탐색
for(File subdir : list) { //subdir(자식 폴더)에 list[] 값 복사
if(subdir.isDirectory()) { //subdir가 폴더면
dirCount++; //폴더 값 증가
count(subdir); //재귀 메소드 -> 자식 폴더가 없을때까지 무한루프
}
}
}
'[JAVA] 정리 > 파일(file)' 카테고리의 다른 글
| 파일(file) - 7. 텍스트 입출력_파일 쓰기 OutputStream(덮어쓰기, 이어쓰기) (0) | 2023.02.27 |
|---|---|
| 파일(file) - 6. 텍스트 입출력_기본 지식 (0) | 2023.02.27 |
| 파일(file) - 4. 파일 조작(재귀 메소드) (0) | 2023.02.27 |
| 파일(file) - 3. 폴더 조작하기(새폴더 만들기, 폴더명 수정, 이동하기, 폴더 삭제하기) (0) | 2023.02.26 |
| 파일(file) - 2. 파일 조작(새로 만들기, 파일명 수정, 파일 이동, 파일 삭제) (0) | 2023.02.26 |