Programing

Java에서 특정 디렉토리의 파일을 반복하는 방법은 무엇입니까?

lottogame 2020. 8. 21. 08:24
반응형

Java에서 특정 디렉토리의 파일을 반복하는 방법은 무엇입니까? [복제]


중복 가능성 :
Java의 디렉토리를 반복하는 가장 좋은 방법은 무엇입니까?

Java를 사용하여 특정 디렉토리의 각 파일을 처리하고 싶습니다.

이 작업을 수행하는 가장 쉽고 일반적인 방법은 무엇입니까?


에 디렉토리 이름이있는 myDirectoryPath경우

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }

나는 당신이 원하는 것을 만드는 데는 많은 방법이 있다고 생각합니다. 여기 제가 사용하는 방법이 있습니다. 으로 commons.io도서관 당신은 디렉토리에있는 파일을 반복 할 수 있습니다. FileUtils.iterateFiles방법을 사용해야하며 각 파일을 처리 할 수 ​​있습니다.

여기에서 정보를 찾을 수 있습니다. http://commons.apache.org/proper/commons-io/download_io.cgi

예를 들면 다음과 같습니다.

Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
        while(it.hasNext()){
            System.out.println(((File) it.next()).getName());
        }

null필터링하고 싶다면 확장자 목록을 변경 하고 넣을 수 있습니다 . 예:{".xml",".java"}


다음은 내 데스크탑에있는 모든 파일을 나열하는 예입니다. 경로 변수를 경로로 변경해야합니다.

System.out.println을 사용하여 파일 이름을 인쇄하는 대신 파일에서 작동 할 고유 한 코드를 배치해야합니다.

public static void main(String[] args) {
    File path = new File("c:/documents and settings/Zachary/desktop");

    File [] files = path.listFiles();
    for (int i = 0; i < files.length; i++){
        if (files[i].isFile()){ //this line weeds out other directories/folders
            System.out.println(files[i]);
        }
    }
}

사용 java.io.File.listFiles은
또는
당신이 이전에 반복 (또는 더 복잡한 사용 사례)에 목록을 필터링하려면, 아파치 - 평민에게 Fileutils의를 사용합니다. FileUtils.listFiles

참고 URL : https://stackoverflow.com/questions/4917326/how-to-iterate-over-the-files-of-a-certain-directory-in-java

반응형