我正在尝试使用Apache VFS2将文件上传到SFTP服务器。使用WinSCP等客户端时,SFTP正常运行。我举了一些互联网上使用Java客户端的示例,但是我一直在出错。使用的版本是2.3。代码:
public class SftpPersister
{
private static final Logger logger = Logger.getLogger( SftpPersister.class );
String serverAddress = "ftp.domain.com";
String user = "myuser";
String password = "mypass";
String remoteDirectory = "outgoing/";
String localDirectory = "c:/users/user/";
public static void main( String[] args )
{
new SftpPersister().upload( "ntuser.ini" );
}
public boolean upload( String fileName )
{
StandardFileSystemManager manager = new StandardFileSystemManager();
try
{
//check if the file exists
String filepath = localDirectory + fileName;
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:///" + user + ":" + password + "@" + serverAddress + "/" + remoteDirectory + fileName;
// 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 );
logger.info( "File upload successful" );
}
catch ( Exception e )
{
logger.error( "failure", e );
return false;
}
finally
{
manager.close();
}
return true;
}
}
执行行remoteFile.copyFrom(localFile,Selectors.SELECT_SELF)时引发异常:
1 [main] ERROR com.company.middletier.storage.SftpPersister - failure
org.apache.commons.vfs2.FileSystemException: Could not find file with URI "sftp:///myuser:***@ftp.domain.com/outgoing/ntuser.ini" because it is a relative path, and no base URI was provided.
at org.apache.commons.vfs2.FileSystemException.requireNonNull(FileSystemException.java:87)
at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:733)
at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:653)
at com.company.middletier.storage.SftpPersister.upload(SftpPersister.java:63)
at com.company.middletier.storage.SftpPersister.main(SftpPersister.java:31)
是配置问题还是我缺少的其他东西?
答案 0 :(得分:4)
0-increment
对jsch的隐含依赖性帮助我解决了这个问题
答案 1 :(得分:1)
似乎jsch是必需的运行时依赖项,需要将其添加到POM文件中。不确定在文档中提到过。添加完成后,所有工作都会顺利进行。
答案 2 :(得分:0)
对于 Gradle 构建,将以下依赖项添加到 build.gradle 文件。
compile group: 'com.jcraft', name: 'jsch', version: '0.1.55'
不幸的是,下面提到的 jcraft 依赖对我不起作用
implementation group: 'com.jcraft', name: 'jsch', version: '0.1.44-1'