[java] Apache Commons VFS를 사용한 파일 검색

Apache Commons VFS는 Java 언어로 작성된 라이브러리로, 다양한 파일 시스템에 대한 표준화된 API를 제공합니다. 이 라이브러리를 사용하면 로컬 파일 시스템뿐만 아니라 FTP, SFTP, HTTP 등 다른 프로토콜로 접근 가능한 파일 시스템에 쉽게 접근할 수 있습니다. 이번 포스트에서는 Apache Commons VFS를 사용하여 파일 검색을 수행하는 방법에 대해 알아보겠습니다.

1. 의존성 설정

먼저 Apache Commons VFS를 사용하기 위해 Maven 또는 Gradle을 이용해 해당 라이브러리의 의존성을 설정해줍니다.

Maven:

<dependency>
    <groupId>commons-vfs</groupId>
    <artifactId>commons-vfs2</artifactId>
    <version>2.8.0</version>
</dependency>

Gradle:

implementation 'commons-vfs:commons-vfs2:2.8.0'

2. 파일 검색 예제

다음은 로컬 파일 시스템에서 특정 디렉토리부터 시작하여 파일 검색을 수행하는 예제 코드입니다. findFiles 메서드는 재귀적으로 디렉토리를 탐색하면서 지정된 확장자를 가진 모든 파일을 찾습니다.

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.FileTypeSelector;
import org.apache.commons.vfs2.impl.DefaultFileSelector;
import org.apache.commons.vfs2.impl.FileDepthSelector;
import org.apache.commons.vfs2.impl.FileExtensionSelector;
import org.apache.commons.vfs2.impl.FileSelectorUtils;
import org.apache.commons.vfs2.impl.SftpFileSystemConfigBuilder;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;

import java.util.ArrayList;
import java.util.List;

public class FileSearchExample {
    public static void main(String[] args) {
        String rootDirPath = "/path/to/root/dir";
        String fileExtension = "txt";

        List<FileObject> foundFiles = new ArrayList<>();
        try {
            StandardFileSystemManager manager = new StandardFileSystemManager();
            manager.init();

            FileObject rootDir = manager.resolveFile(rootDirPath);
            FileObject[] files = rootDir.findFiles(new FileExtensionSelector(fileExtension));

            for (FileObject file : files) {
                if (file.getType().equals(FileType.FILE)) {
                    foundFiles.add(file);
                }
            }

            manager.close();
        } catch (FileSystemException e) {
            e.printStackTrace();
        }

        System.out.println("Found files:");
        for (FileObject file : foundFiles) {
            String filePath = file.getName().getURI();
            System.out.println(filePath);
        }
    }
}

위의 코드에서 rootDirPath 변수에는 검색을 시작할 디렉토리의 경로를, fileExtension 변수에는 검색할 파일의 확장자를 지정해주어야 합니다. 파일 검색 결과는 foundFiles 리스트에 저장되며, 화면에 출력됩니다.

3. 실행 결과

위의 예제 코드를 실행하면 지정된 디렉토리부터 시작하여 확장자가 “txt”인 모든 파일이 검색되고, 그 경로가 화면에 출력됩니다.

Found files:
/path/to/root/dir/file1.txt
/path/to/root/dir/subdir/file2.txt
/path/to/root/dir/subdir/subsubdir/file3.txt

4. 결론

Apache Commons VFS를 사용하면 다양한 파일 시스템에 대해 일관된 방식으로 파일을 처리할 수 있습니다. 파일 검색과 같은 작업을 수행할 때 유용하게 활용할 수 있으며, 간편한 API를 통해 파일 조작이 가능합니다.

더 자세한 내용은 Apache Commons VFS 공식 문서를 참고하시기 바랍니다.