云计算百科
云计算领域专业知识百科平台

java SFTP从服务器下载文件到指定目录

java SFTP从服务器下载文件到指定目录

  • 1.pom添加依赖
  • 2.初始化SFTP连接
  • 3.下载服务器文件代码
  • 总结:

有时开发会有需求,要从指定服务器下载同步文件到本地服务器,这时就需要使用到SFTP了。

1.pom添加依赖

需要引入依赖jcraft

<!– SFTP –>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>

2.初始化SFTP连接

需要在对应的类设置好参数,如果需要在配置文件里设置,则可以设置为启动配置类。 username:帐号 hostname:服务器ip port:端口号,一般默认为22 password:密码 要先保证你用这些配置在sftp连接工具上能够正常连接到服务器,不然你用程序连也是连不上的。

private Session initASession() {
JSch jsch = new JSch();
Session sftpSession = null;
try {
sftpSession = jsch.getSession(username, hostname, port);
sftpSession.setPassword(password);
sftpSession.setConfig("StrictHostKeyChecking", "no"); // 设置为不检查主机密钥,若有特殊需求要进行设置
} catch (JSchException e) {
log.error("初始化sftp失败!");
}
return sftpSession;
}

3.下载服务器文件代码

remoteFilePath参数:要下载的远程文件路径
localFilePath: 下载到指定的本地路径

public void downLoadOneFileToLocal(String remoteFilePath, String localFilePath) {
Session sftpSession = null;
Channel channel=null;
ChannelSftp sftpChannel=null;
try {
sftpSession = this.initASession();
sftpSession.connect();
channel = sftpSession.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp) channel;
log.info("开始下载文件,远程路径文件["+remoteFilePath+"].本地路径文件:["+localFilePath+"]");
sftpChannel.get(remoteFilePath, localFilePath); // 下载
} catch (JSchException | SftpException e) {
log.error("downLoadOneFileToLocal error!",e);
log.error("执行method-downLoadOneFileToLocal-错误信息:{"+ e.getMessage()+"}");
}finally {
//释放资源
if (sftpChannel!=null) {
try {
sftpChannel.exit();
}catch (Exception ignored){}
}
if (channel!=null) {
try {
channel.disconnect();
}catch (Exception ignored){}
}
if (sftpSession!=null) {
try {
sftpSession.disconnect();
}catch (Exception ignored){}
}
}
}

代码执行 代码执行后可看到指定目录有文件。

总结:

1.pom引入依赖 2.配置好服务器的IP、端口和帐号密码等信息 3.初始化sftpSession连接 4.执行方法下载文件

实际代码可根据开发需求修改。例如:将指定服务器目录下的文件都下载到指定本地目录、

赞(0)
未经允许不得转载:网硕互联帮助中心 » java SFTP从服务器下载文件到指定目录
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!