2014-10-19 103 views
0

我試圖使用org.apache.commons.vfs2通過SFTP下載文件。 問題是,密碼包含「@」字符,所以這將導致URI進行解析不正確:Java SFTP(apache vfs2) - 密碼@

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); 
+0

再來看看你的'sftpUri'。如果您的密碼包含@,那麼'remoteServerAddress'參數會發生什麼? – Hannes 2014-10-19 13:37:56

+0

正如我所說的,我知道問題是什麼(由於密碼中的@,URI被不正確地解析)。我的問題是如何解決它。 – Ayelet 2014-10-19 13:39:55

+1

Sry。我沒看見。看看http://stackoverflow.com/questions/6718471/escaping-username-characters-in-basic-auth-urls – Hannes 2014-10-19 13:42:19

回答

2

使用an actual URI constructor代替手卷自己:

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); 
+0

並確保路徑以/開頭,並且不使用Windows \角色。或者你從這樣的文件轉換它:'new File(「c:\\ temp」)。toURI()。getPath()' – eckes 2015-01-05 17:33:53