초보 프로그램 개발자

[ 5주차 ] Java - FileFilter 본문

교육 일지/java

[ 5주차 ] Java - FileFilter

Ji_HG 2023. 5. 31. 17:08
FileFilter
  • 특정 경로 폴더 안의 내용을 모두 읽어오는 Interface
  • Interface 이기 때문에 무조건 accept를 오버라이드 해주어야 한다.
package com.day19;

import java.io.File;
import java.io.FileFilter;

// 특정 경로 폴더안의 내용을 모두 읽어오는 클래스

class MyFileList implements FileFilter{

	private File f;
	
	public MyFileList(String path) {
		f = new File(path);
	}
	
	public void result() {
		
		try {
			
			if(!f.exists()) { // 파일이 없을경우
				System.out.println("파일이 없습니다.");
			}
			
			System.out.println("경로 : " + f.getAbsolutePath());
			System.out.println("파일크기 : " + f.length());
			
			// 파일이 아니라 폴더인 경우
			if(f.isDirectory()) {
				File[] lists = f.listFiles(this);
				// 폴더내용 출력
				System.out.println("\n폴더 내용....");
				
				for(int i=0; i<lists.length; i++) {
					System.out.print("폴더이름 : " + lists[i].getName());
					System.out.println("\t폴더크기 : " + lists[i].length());
				}
			}
			System.out.println("-----------------------");
			System.out.println("\n디렉토리 내용...");
			
			// File.listRoots() 는 드라이브를 표시 (c:, d:...)
			File[] root = File.listRoots();
			
			for(int i=0; i<root.length; i++) {
				System.out.println(root[i].getPath());
			}
			
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		
	}
	
	@Override
	public boolean accept(File pathname) {
		return pathname.isFile() || pathname.isDirectory();
	}
}

public class Test13 {
	
	public static void main(String[] args) {
		
		MyFileList mf = new MyFileList("c:\\");
		
		mf.result();
	}
}