ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java에서 폴더 내 모든 파일을 탐색하는 방법
    카테고리 없음 2025. 2. 10. 20:42
    반응형

    Java에서 폴더 내 모든 파일을 탐색하는 방법

    Java에서 폴더와 그 하위 폴더의 모든 파일을 탐색하는 방법을 알아보겠습니다. Files.walk() API를 사용하여 이를 쉽게 구현할 수 있습니다.

    1. 폴더 내 모든 파일 탐색하기

    먼저, 단일 폴더 내의 모든 파일을 탐색하는 예제를 살펴보겠습니다.

    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 FileTraverseExample {
        public static void main(String[] args) {
            String dirPath = "/Users/username/projects/test/";
    
            try (Stream<Path> paths = Files.walk(Paths.get(dirPath))) {
                paths
                    .filter(Files::isRegularFile)
                    .forEach(System.out::println);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    이 코드는 지정된 디렉토리의 모든 파일 경로를 출력합니다.

    2. 폴더와 하위 폴더의 모든 파일 탐색하기

    Files.walk() API는 기본적으로 하위 폴더까지 탐색합니다. 따라서 위의 코드를 그대로 사용하면 됩니다.

    3. 폴더 내 모든 파일 이름 나열하기

    파일 이름만 수집하고 싶다면 다음과 같이 코드를 수정할 수 있습니다:

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.List;
    import java.util.stream.Stream;
    
    public class FileTraverseExample2 {
        public static void main(String[] args) {
            String dirPath = "/Users/username/projects/test/";
    
            try (Stream<Path> paths = Files.walk(Paths.get(dirPath))) {
                List<String> result = paths
                    .filter(Files::isRegularFile)
                    .map(p -> p.getFileName().toString())
                    .toList();
    
                System.out.println("Total files: " + result.size());
                result.forEach(name -> System.out.println("FileName: " + name));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    이 코드는 총 파일 수와 각 파일의 이름을 출력합니다.

    4. 특정 파일 찾기

    특정 파일을 찾고 싶다면 다음과 같이 구현할 수 있습니다:

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.Optional;
    import java.util.stream.Stream;
    
    public class FileTraverseExample3 {
        public static void main(String[] args) {
            String dir = "/Users/username/projects/test/";
            String findThisFile = "a.txt";
    
            try {
                Optional<Path> foundFile = findFileByName(Paths.get(dir), findThisFile);
                foundFile.ifPresentOrElse(
                    file -> System.out.println("File found: " + file),
                    () -> System.out.println("File not found.")
                );
            } catch (IOException e) {
                System.err.println("An error occurred while searching for the file: " + e.getMessage());
            }
        }
    
        public static Optional<Path> findFileByName(Path directory, String fileName) throws IOException {
            try (Stream<Path> stream = Files.walk(directory)) {
                return stream
                    .filter(Files::isRegularFile)
                    .filter(path -> path.getFileName().toString().equals(fileName))
                    .findFirst();
            }
        }
    }

    이 코드는 지정된 디렉토리와 그 하위 디렉토리에서 특정 파일을 찾아 그 경로를 반환합니다.

    결론

    Java의 Files.walk() API를 사용하면 폴더 내의 모든 파일을 쉽게 탐색할 수 있습니다. 이 방법은 파일 시스템 작업을 수행할 때 매우 유용하며, 스트림 API와 결합하여 강력한 파일 처리 기능을 제공합니다.

    반응형
Designed by Tistory.