这可能是一个答案...
我遇到了完全相同的问题 - 只是第一次对我有用,但在以后的尝试中却没有!
我有一个我经常调用的方法,它将文件的副本上传到 SFTP 服务器上的不同文件夹:
private static void copyToSftpLocations(...)
{
[...]
try (FileSystemManager manager = VFS.getManager())
{
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setSessionTimeout(opts, java.time.Duration.ofMillis(sftpSessionTimeout));
SftpFileSystemConfigBuilder.getInstance().setConnectTimeout(opts, java.time.Duration.ofMillis(sftpSessionTimeout));
SftpFileSystemConfigBuilder.getInstance().setPreferredAuthentications(opts, "publickey,keyboard-interactive,password");
SftpFileSystemConfigBuilder.getInstance().setKnownHosts(opts, new File("known_hosts.txt"));
LOG.debug("Attempting to connect to "+sftpServer+" as "+sftpUserName+"...");
try (FileObject remoteServer = manager.resolveFile("sftp://"+URLEncoder.encode(sftpUserName,StandardCharsets.UTF_8.toString())+":"+URLEncoder.encode(sftpPassword,StandardCharsets.UTF_8.toString())+"@"+sftpServer,opts))
{
while (...)
{
String sftpDirName = ...;
String remotePath = "/"+sftpDirName;
try (FileObject remoteFolder = remoteServer.resolveFile(remotePath))
{
if (!remoteFolder.exists())
{
remoteFolder.createFolder();
}
try (FileObject local = manager.resolveFile(theMasterPath.toUri());
FileObject remoteFile = remoteFolder.resolveFile(theMasterPath.getFileName().toString()))
{
remoteFile.copyFrom(local, Selectors.SELECT_SELF);
}
我第一次调用该方法时,一切正常 - 每个文件夹中的文件副本。
我第二次及以后调用该方法时,我得到了:
org.apache.commons.vfs2.FileSystemException: Could not find file with URI "sftp://<user>:***@<address>" because it is a relative path, and no base URI was provided.
我在创建 FileObject remoteServer 时尝试使用 sftpServer+"/",但没有任何区别。
我根本不明白为什么最初有效的东西没有继续有效。此外,基本上相同的代码在我的项目中的其他地方使用,并且每次都有效!
我正在使用 commons-vfs2 2.9.0 版。
edit:我刚刚发现,如果我删除第一个 try-resource 并放入
FileSystemManager manager = VFS.getManager();
改为显式调用,一切正常...!