Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 디렉토리에서 파일을 검색하는 방법

<시간/>

목록() File 클래스의 메소드는 현재 (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

문자열[] 목록(FilenameFilter 필터) File 클래스의 메소드는 현재 (File) 객체가 나타내는 경로에 있는 모든 파일 및 디렉토리의 이름을 포함하는 String 배열을 반환합니다. 그러나 재조정된 배열에는 지정된 필터를 기반으로 필터링된 파일 이름이 포함됩니다. 파일 이름 필터 단일 메소드를 사용하는 Java의 인터페이스입니다.

accept(파일 디렉토리, 문자열 이름)

파일 이름을 검색하려면 원하는 파일 이름과 일치하는 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