FileVisitor — 파일 방문자 인터페이스

FileVisitor — 파일 방문자 인터페이스

파일 트리를 순회하면서 각 파일을 방문할 때 호출되는 콜백 메서드를 정의하는 인터페이스예요. Files.walkFileTree 메서드에 이 인터페이스의 구현을 넘겨 파일 트리의 각 파일을 방문하게 해요. 순회 중 디렉터리 진입 전, 파일 방문, 방문 실패, 디렉터리 방문 후 등 네 시점에 대응하는 메서드가 있어요.

출처: Java API Reference

본문

  • FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) throws IOException — 디렉터리의 항목들을 방문하기 전에 해당 디렉터리에 대해 호출돼요. 반환값에 따라 디렉터리 항목을 계속 방문할지(CONTINUE), 건너뛸지(SKIP_SUBTREE)가 결정돼요.
  • FileVisitResult visitFile(T file, BasicFileAttributes attrs) throws IOException — 디렉터리에 있는 파일에 대해 호출돼요. 파일의 기본 속성은 attrs로 전달돼요.
  • FileVisitResult visitFileFailed(T file, IOException exc) throws IOException — 기본 속성을 가져오지 못하거나 어떤 이유로 파일을 방문하지 못했을 때 호출돼요. 예외가 발생한 경우 exc에 그 예외가 담겨요.
  • FileVisitResult postVisitDirectory(T dir, IOException exc) throws IOException — 디렉터리의 항목들과 그 모든 하위 항목들을 방문한 뒤 해당 디렉터리에 대해 호출돼요. 디렉터리를 방문하는 동안 I/O 오류가 발생하면 exc에 그 예외가 담겨요.

사용 예시 — 파일 트리 삭제

각 디렉터리는 그 안의 항목들을 삭제한 뒤에 삭제해야 해요. visitFile에서 파일을 삭제하고, postVisitDirectory에서 디렉터리를 삭제하면 돼요.

Path start = ...;
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {{
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {{
        Files.delete(file);
        return FileVisitResult.CONTINUE;
    }}
    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {{
        if (e == null) {{
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }} else {{
            // 디렉터리 순회 실패
            throw e;
        }}
    }}
}});

더 알아보기 (Learn more)