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

Java의 디렉토리에서 jpg 파일 목록을 얻는 방법은 무엇입니까?

<시간/>

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

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

확장자를 기반으로 하는 파일 이름을 가져오려면 이 인터페이스를 그대로 구현하고 해당 개체를 파일 클래스의 위에서 지정한 list() 메서드에 전달합니다.

ExampleDirectory라는 폴더가 있다고 가정합니다. 디렉토리 D 7개의 파일과 2개의 디렉토리가 있는 -

Java의 디렉토리에서 jpg 파일 목록을 얻는 방법은 무엇입니까?

다음 Java 프로그램은 D:\\ExampleDirectory 경로에 있는 텍스트 파일 및 jpeg 파일의 이름을 인쇄합니다. 별도로.

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class Sample{
   public static void main(String args[]) throws IOException {
    //Creating a File object for directory
    File directoryPath = new File("D:\\ExampleDirectory");
    //Creating filter for jpg files
    FilenameFilter jpgFilefilter = new FilenameFilter(){
         public boolean accept(File dir, String name) {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".jpg")) {
               return true;
            } else {
               return false;
            }
         }
      };        
      String imageFilesList[] = directoryPath.list(jpgFilefilter);
      System.out.println("List of the jpeg files in the specified directory:");  
      for(String fileName : imageFilesList) {
         System.out.println(fileName);
      }  
   }
}

출력

List of the jpeg files in the specified directory:
cassandra_logo.jpg
cat.jpg
coffeescript_logo.jpg
javafx_logo.jpg

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Example {
   public static void main(String[] args) throws IOException {
      Stream<Path> path = Files.walk(Paths.get("D:\\ExampleDirectory"));
      path = path.filter(var -> var.toString().endsWith(".jpg"));
      path.forEach(System.out::println);
    }
}

출력

List of the jpeg files in the specified directory:
cassandra_logo.jpg
cat.jpg
coffeescript_logo.jpg
javafx_logo.jpg