首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Apache Commons Vfs2传输SFTP文件

使用Apache Commons Vfs2传输SFTP文件
EN

Stack Overflow用户
提问于 2017-06-07 19:03:00
回答 1查看 3.4K关注 0票数 0

我正在使用Apache Commons VFS2上传一个文件到服务器。下面是相同的代码。我所有的证书都是正确的。代码还打印了"File uploaded“字符串。但是,当我交叉检查时,我在服务器上找不到该文件。我在代码中遗漏了什么吗?

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

代码语言:javascript
运行
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2017-06-07 19:45:28

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

代码语言:javascript
运行
复制
String sftpUri =
    "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory + "/" +
    file.getName(); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44410860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档