2011-02-07 4 views
77

가능한 중복 :
Best way to iterate through a directory in java?Java에서 특정 디렉토리의 파일을 반복하는 방법은 무엇입니까?

내가 자바를 사용하여 특정 디렉토리의 각 파일을 처리하려고합니다.

가장 쉬운 방법은 무엇입니까? 당신이 myDirectoryPath 디렉토리 이름이있는 경우

+2

중복 : http://stackoverflow.com/questions/3154488/best-way-to-iterate-through-a-directory-in-java – Olhovsky

답변

139

,

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. 
    } 
+1

Javado는 listFiles()에서 " 디렉토리 자체와 디렉토리의 상위 디렉토리는 결과에 포함되지 않습니다. " – pihentagy

+0

@pihentagy, 나는 그것을 몰랐다. 감사. –

+1

fyi 현재 폴더를 원한다면'new File ("."); ' – Csanesz

6

여기 내 바탕 화면에있는 모든 파일을 나열하는 예입니다. 경로 변수를 경로로 변경해야합니다.

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]); 
     } 
    } 
} 
3

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

+0

'listFiles'는 파일 필터 또는 파일 이름 필터를 사용하기 위해 무시됩니다. 그래서 원하는 유일한 것이 필터링 인 경우 apache-commons를 사용할 필요가 없습니다. 그것은 훌륭한 도서관이지만. –

27

나는 원하는대로 만들 수있는 많은 방법이 있다고 생각합니다. 여기 제가 사용하는 방법이 있습니다. 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"}

+0

제 3 자 라이브러리를 사용하지 않으려 고했지만 Apache의 FileUtil에는 유용한 메소드가 많이있는 것 같습니다. 감사. +1 –

+0

예 ... 사실 아파치의 모든 커먼 라이브러리는 정말 훌륭합니다. 코드 작성에 많은 시간이 걸릴 수 있습니다. Commons.collections는 또 다른 좋은 예입니다. – jomaora

+3

@ john-assymptoth,이 라이브러리가 없으면 라이브러리에 파일이 많이 포함되어있는 경우 java를 구현 한 util 만 'StackOverflowError'로 구동합니다. (http://java.sun.com/javase/6/docs/api/java/lang/StackOverflowError.html) – Rihards

관련 문제