Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 디렉토리 내 파일 검색하는 방법 완벽 가이드

Java에서 특정 디렉토리 안에 원하는 파일이 있는지 확인하고 싶다면 File 클래스가 제공하는 메서드를 활용할 수 있습니다. 이 글에서는 두 가지 대표적인 방법을 예제 코드와 함께 소개합니다.

1. list() 메서드로 전체 파일 목록 조회 후 비교하기

File 클래스의 list() 메서드는 현재 File 객체가 나타내는 경로에 존재하는 모든 파일과 디렉터리의 이름을 String 배열 형태로 반환합니다.

따라서 특정 파일을 검색하려면 반환된 배열을 순회하면서 equals() 메서드로 각 항목의 이름과 찾고자 하는 파일 이름을 일일이 비교하면 됩니다.

예제 코드

import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class Example {
    public static void main(String[] argv) throws Exception {
        System.out.println("Enter the directory path: ");
        Scanner sc = new Scanner(System.in);
        String pathStr = sc.next();
        System.out.println("Enter the desired file name: ");
        String file = sc.next();
        System.out.println(file);
        File dir = new File(pathStr);
        String[] list = dir.list();
        System.out.println(Arrays.toString(list));
        boolean flag = false;
        for (int i = 0; i < list.length; i++) {
            if(file.equals(list[i])){
                flag = true;
            }
        }
        if(flag){
            System.out.println("File Found");
        }else{
            System.out.println("File Not Found");
        }
    }
}

실행 결과

Enter the directory path:
D:\ExampleDirectory
Enter the desired file name:
demo2.pdf
demo2.pdf
[demo1.pdf, demo2.pdf, sample directory1, sample directory2, sample directory3, sample directory4, sample_jpeg1.jpg, sample_jpeg2.jpg, test1.docx, test2.docx]
File Found

2. FilenameFilter를 활용한 필터링 검색

두 번째 방법은 list(FilenameFilter filter) 메서드를 사용하는 것입니다. 이 메서드 역시 현재 File 객체가 나타내는 경로의 모든 파일과 디렉터리 이름을 String 배열로 반환하지만, 지정된 필터 조건에 맞는 파일명만 골라서 담아준다는 점이 다릅니다.

FilenameFilter는 단 하나의 메서드만 가지는 인터페이스입니다.

accept(File dir, String name)

파일을 검색하려면 찾고자 하는 파일 이름과 일치하는지 판단하는 FilenameFilter 구현체를 만들어 전달하면 됩니다.

예제 코드

import java.io.File;
import java.io.FilenameFilter;
public class Example {
    public static void main(String[] argv) throws Exception {
        File dir = new File("D:\\ExampleDirectory");
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.equalsIgnoreCase("demo1.pdf");
            }
        };
        String[] files = dir.list(filter);
        if (files == null) {
            System.out.println("File Not Found");
        }else {
            System.out.println("File Found");
        }
    }
}

실행 결과

File Found

정리

디렉토리 내 파일 검색은 크게 두 가지 방식으로 구현할 수 있습니다. 첫 번째 방법은 list() 메서드로 전체 목록을 가져온 뒤 직접 비교하는 방식으로, 로직이 단순하고 직관적입니다. 두 번째 방법은 FilenameFilter 인터페이스를 활용해 조건에 맞는 파일만 미리 걸러내는 방식으로, 대상이 많을 때 더 효율적이며 코드도 깔끔하게 유지할 수 있습니다. 상황에 맞게 적절한 방법을 선택해 활용해 보세요.