반응형
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
반응형
'Programing' 카테고리의 다른 글
EGit 및 GitHub의 '인증 실패'오류 (0) | 2020.08.21 |
---|---|
도메인 특정 언어는 무엇입니까? (0) | 2020.08.21 |
iPhone의 날짜 문자열에서 밀리 초 동안 어떤 형식 문자열을 사용합니까? (0) | 2020.08.21 |
IntelliJ에서 실행할 때 Spring Boot 프로필을 어떻게 활성화합니까? (0) | 2020.08.21 |
Swift에서 실패 가능한 이니셜 라이저를 구현하는 모범 사례 (0) | 2020.08.21 |