【发布时间】:2026-01-22 19:35:01
【问题描述】:
我正在尝试使用 Apache Commons VFS 将文件 SFTP 到服务器上,但我不断收到以下错误:
java.lang.RuntimeException: org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "sftp://user:***@xxx.x.xxx.xxx/".
这里不包含远程文件路径(remoteFilePath)是否正常?在我的代码中将其包含在连接字符串中(见下文)
我的 pom 中包含以下 jars:
commons-logging-1.1.3.jar
commons-vfs2-2.0.jar
hamcrest-core-1.3.jar
jsch-0.1.50.jar
代码:
public void SftpMethod(String strMsg, String tableName){
String host = "xxx.x.xxx.xxx";
String user = "user";
String pass = "password!";
String localFilePath = "C:\\Users\\exampleDir\\Desktop\\loc.dat";
String remoteFilePath = "/dir/home/user/export/loc.dat";
StandardFileSystemManager manager = new StandardFileSystemManager();
File file = new File(localFilePath);
if (!file.exists())
throw new RuntimeException("Error. Local file not found");
try{
manager.init();
// Create local file object
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(
createConnectionString(host, user, pass, remoteFilePath),
createDefaultOptions());
// Copy local file to SFTP server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("File upload success");
}catch(IOException e){
throw new RuntimeException(e);
}finally{
manager.close();
}
}
public static String createConnectionString(String hostName, String username, String password, String remoteFilePath) {
return "sftp://" + username + ":" + password + "@" + hostName + "/" + remoteFilePath;
}
public static FileSystemOptions createDefaultOptions() throws FileSystemException {
// Create SFTP options
FileSystemOptions opts = new FileSystemOptions();
// SSH Key checking
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
/*
* Using the following line will cause VFS to choose File System's Root
* as VFS's root. If I wanted to use User's home as VFS's root then set
* 2nd method parameter to "true"
*/
// Root directory set to user home
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
// Timeout is count by Milliseconds
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
return opts;
}
【问题讨论】:
-
@Ram,感谢您的编辑建议
-
欢迎。我希望你的问题能尽快得到解答。祝你好运。
-
能否包含异常的完整堆栈跟踪?
-
我遇到了同样的问题。你有没有解决这个问题。
标签: java apache maven sftp vfs