使用Apache Commons Vfs2进行SFTP文件传输

时间:2017-06-07 11:03:00

标签: java sftp apache-commons-vfs

我正在使用Apache Commons VFS2将文件上传到服务器。下面是相同的代码。我拥有所有凭据。代码已打印"文件已成功上传"字符串也是如此。但是,当我交叉检查时,我无法在服务器上找到该文件。我在代码中缺少什么?

我需要所有的Jars(Apache Commons VFS jar,JSH jar)

public static void main(String[] args) {

    SendMyFiles sendMyFiles = new SendMyFiles();

    sendMyFiles.startFTP("C:/useragent.log");

}

public boolean startFTP(String fileToFTP) {

    props = new Properties();
    StandardFileSystemManager manager = new StandardFileSystemManager();

    try {

        // props.load(new FileInputStream("properties/" +
        // propertiesFilename));
        String serverAddress = "10.111.111.11";
        String userId = "username";
        String password = "password";
        String remoteDirectory = "local/home/client/files/";

        // check if the file exists
        String filepath = fileToFTP;
        File file = new File(filepath);
        if (!file.exists())
            throw new RuntimeException("Error. Local file not found");

        // Initializes the file manager
        manager.init();

        // Setup our SFTP configuration
        FileSystemOptions opts = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

        // Create the SFTP URI using the host name, userid, password, remote
        // path and file name
        String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory;

        // Create local file object
        FileObject localFile = manager.resolveFile(file.getAbsolutePath());

        // Create remote file object
        FileObject remoteFile = manager.resolveFile(sftpUri, opts);

        // Copy local file to sftp server
        remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
        System.out.println("File upload successful");

    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    } finally {
        manager.close();
    }

    return true;
}

1 个答案:

答案 0 :(得分:1)

我假设sftpUri应该是目标文件的路径,而不是目录:

String sftpUri =
    "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory + "/" +
    file.getName();