Programming/JAVA

[Apache VFS] SFTP 파일 업로드

빈쿵바라기 2023. 3. 8. 19:03

공식 Document : Commons Virtual File System

 

Apache Commons VFS – Commons Virtual File System

Commons Virtual File System Commons VFS provides a single API for accessing various different file systems. It presents a uniform view of the files from various different sources, such as the files on local disk, on an HTTP server, or inside a Zip archive.

commons.apache.org

 

1. Dependency 추가

<!-- Apache Commons VFS -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-vfs2</artifactId>
    <version>2.9.0</version>
</dependency>

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
  • 기본적으로 vfs2 의존성을 넣어주면 됩니다.
  • 하지만, jsch 를 넣어주지 않으면 sftp 로 전송을 할 수 없습니다.(vfs2 패키지에서 JSch를 필요로 합니다.)

 

2. Sample Code

public void upload(File file) throws FileSystemException {
    FileSystemManager manager = VFS.getManager();
    FileSystemOptions fileOpt = new FileSystemOptions();
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fileOpt, false);

    try (
            FileObject local = manager.resolveFile(file.getPath());
            FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + hostName + remoteFilePath, fileOpt);
        )
    {

        remote.copyFrom(local, Selectors.SELECT_SELF);

        log.info("file upload success");

    } catch (Exception e) {
        log.info("file upload failed");
        e.printStackTrace();
    }

}

copyForm() 메소드가 실행이되면서 remote에 업로드가 됩니다.

SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fileOpt, false); 를 통해 UserDirlsRoot를 false하면(default true) home 디렉터리가 아닌 root 디렉터리에서부터 경로를 탐색하여 저장합니다.

예를 들어 /opt/data에 저장한다고 할 때 UserDirIsRoot = true라면 /home/username/opt/data에 저장을 하고 false라면 /opt/data에 저장하게 됩니다.

 

* 주의점

password에 #이나 @들어가면 오류 발생