ListFiles() 메서드는 현재(File) 개체가 나타내는 경로에 있는 모든 파일(및 디렉터리)의 개체(추상 경로)를 포함하는 배열을 반환합니다.
파일 필터 인터페이스는 listFiles() 메소드에 매개변수로 전달할 수 있는 경로 이름에 대한 필터입니다. 이 메서드는 전달된 필터에 전달된 파일 이름을 필터링합니다.
폴더의 디렉토리를 가져오려면 빈 디렉토리만 허용하는 FileFilter를 구현하고 매개변수로 listFiles() 메서드에 전달합니다.
예시
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class MyExample{
public static void main(String args[]) throws IOException {
//Creating a File object for directory
File directoryPath = new File("D:\\ExampleDirectory");
//Creating filter for directories files
FileFilter fileFilter = new FileFilter(){
public boolean accept(File dir) {
if (dir.isDirectory()&& dir.list().length==0) {
return true;
} else {
return false;
}
}
};
File[] list = directoryPath.listFiles(fileFilter);
System.out.println("List of the jpeg files in the specified directory:");
for(File fileName : list) {
System.out.println(fileName.getName());
System.out.println(fileName);
}
}
} 출력
List of the jpeg files in the specified directory: sample directory1 D:\ExampleDirectory\sample directory1