[java] Apache Commons VFS를 사용한 FTP 파일 전송

이번에는 Apache Commons VFS 라이브러리를 사용하여 FTP 서버와 파일을 전송하는 방법을 알아보겠습니다. Apache Commons VFS는 다양한 파일 시스템에 접근할 수 있는 공통 인터페이스를 제공하는 라이브러리입니다. FTP를 비롯한 다양한 파일 시스템을 쉽게 다룰 수 있으며, 이를 활용하여 파일 전송 기능을 구현할 수 있습니다.

1. 의존성 추가

먼저, 프로젝트에 Apache Commons VFS를 추가해야 합니다. Maven을 사용하는 경우, pom.xml 파일에 다음 의존성을 추가합니다.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-vfs2</artifactId>
    <version>2.8.0</version>
</dependency>

Gradle을 사용하는 경우, build.gradle 파일에 다음 의존성을 추가합니다.

implementation 'org.apache.commons:commons-vfs2:2.8.0'

의존성을 추가한 후, 프로젝트를 업데이트 해줍니다.

2. FTP 파일 전송 코드 구현

이제 FTP 파일 전송을 위한 코드를 구현해보겠습니다.

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;

public class FTPFileTransfer {

    public static void main(String[] args) {
        String serverUrl = "ftp.example.com";
        String username = "ftp_username";
        String password = "ftp_password";
        String localFilePath = "path/to/local/file.txt";
        String remoteFilePath = "/path/on/remote/file.txt";

        StandardFileSystemManager manager = new StandardFileSystemManager();
        try {
            manager.init();

            // FTP 서버 연결 설정
            FileSystemOptions opts = new FileSystemOptions();
            FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
            
            // FTP 서버 연결
            String ftpUrl = "ftp://" + username + ":" + password + "@" + serverUrl + "/" + remoteFilePath;
            FileObject remoteFile = manager.resolveFile(ftpUrl, opts);

            // 로컬 파일
            FileObject localFile = manager.resolveFile(localFilePath);

            // 파일 복사
            remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
            System.out.println("파일 전송이 완료되었습니다.");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            manager.close();
        }
    }
}

위 예제 코드는 ftp.example.com 서버에 ftp_usernameftp_password로 접속하여 path/to/local/file.txt 로컬 파일을 /path/on/remote/file.txt 경로로 전송합니다. 먼저 StandardFileSystemManager 객체를 생성하고, init 메서드를 호출하여 초기화합니다. 그리고 FileSystemOptions 객체를 생성하여 FTP 연결 설정을 지정합니다. ftp:// 프로토콜을 사용하여 FTP 서버에 접속한 후, resolveFile 메서드를 사용하여 로컬 파일과 원격 파일을 가져옵니다. 마지막으로 copyFrom 메서드를 호출하여 파일을 전송하고, 성공 여부를 출력합니다.

3. 실행 결과

위의 예제 코드를 실행하면, 해당 경로에 파일이 성공적으로 전송되었는지 확인할 수 있습니다.

파일 전송이 완료되었습니다.

참고 자료