Java的SFTP(阿帕奇VFS2) - 有密码@(Java SFTP (apache vfs2)

2019-10-21 03:48发布

我试图使用org.apache.commons.vfs2通过SFTP下载文件。 问题是,密码包含“@”字符,所以这将导致URI被正确地分析:

org.apache.commons.vfs2.FileSystemException: Expecting / to follow the hostname in URI

有没有人有一个想法如何解决这个问题? (我不能更改密码,很明显)。 这是我使用的代码:

String sftpUri = "sftp://" + userName + ":" + password + "@"
        + remoteServerAddress + "/" + remoteDirectory + fileName;

String filepath = localDirectory + fileName;
File file = new File(filepath);
FileObject localFile = manager.resolveFile(file.getAbsolutePath());

FileObject remoteFile = manager.resolveFile(sftpUri, opts);
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);

Answer 1:

使用一个实际的URI构造 ,而不是手卷自己:

String userInfo = userName + ":" + password;
String path = remoteDirectory + filename;  // Need a '/' between them?
URI sftpUri = new URI("sftp", userInfo, remoteServerAddress, -1, path, null, null);
...
FileObject remoteFile = manager.resolveFile(sftpUri.toString(), opts);


文章来源: Java SFTP (apache vfs2) - password with @