注:需要java1.7以上支持
引用jar包 commons-logging-1.2.jar,commons-vfs2-2.2.jar
之前用jsch做了sftp上传的功能,由于用户的openssl版本高,需要改配置,但处于安全考虑又不允许修改,所以选用apache的commons来实现文件的上传,一下直接上代码:
public static boolean startSFTP(String host,String username,String password,String localFilePath,String remoteFilePath){
File file = new File(localFilePath);
if (!file.exists()){
throw new RuntimeException("Error. localfile is not found");
}
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder configBuilder = SftpFileSystemConfigBuilder.getInstance();
configBuilder.setStrictHostKeyChecking(opts,"no");
configBuilder.setUserDirIsRoot(opts,true);
configBuilder.setTimeout(opts,10000);
String sftpUri = "sftp://"+username+":"+password+"@"+host+"/"+remoteFilePath;
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
FileObject remoteFile = manager.resolveFile(sftpUri,opts);
remoteFile.copyFrom(localFile,Selectors.SELECT_SELF);
System.out.println("File upload successful");
} catch (FileSystemException e) {
e.printStackTrace();
}finally {
manager.close();
}
return true;
}