java中sftp传输

发布时间:2026/7/15 15:10:35
java中sftp传输 引入jsch 截止目前最新版0.1.55dependency groupIdcom.jcraft/groupId artifactIdjsch/artifactId version0.1.55/version /dependencySftpUtils.javapackage com.ruoyi.manage.sftp01.utils; import com.jcraft.jsch.*; import com.ruoyi.manage.sftp01.SftpProperties; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.annotation.Resource; Slf4j Component public class SftpUtils { private String protocol sftp; private String host; private Integer port; private String username; private String password; public void upload(String sftpPath, File file){ ChannelSftp sftp null; try { InputStream inputStream new FileInputStream(file); sftp this.createSftp(); sftp.cd(sftpPath); sftp.put(inputStream, file.getName()); } catch (Exception e){ log.error(上传文件失败原因{}, e.getMessage(), e); }finally { this.disconnect(sftp); } } public ChannelSftp createSftp() throws JSchException { JSch jsch new JSch(); log.info(Try to connect sftp[ username host ]); Session session createSession(jsch, host , username, port); session.setPassword(password); session.setConfig(StrictHostKeyChecking, no); session.connect(); log.info(Session connected to {}., host); Channel channel session.openChannel(protocol); channel.connect(); log.info(Channel created to {}., host); return (ChannelSftp) channel; } public Session createSession(JSch jsch, String host, String username, Integer port) throws JSchException { Session session null; if (port 0) { session jsch.getSession(username, host); } else { session jsch.getSession(username, host, port); } if (session null) { throw new RuntimeException(host session is null); } return session; } public void disconnect(ChannelSftp sftp) { try { if (sftp ! null) { if (sftp.isConnected()) { sftp.disconnect(); } else if (sftp.isClosed()) { log.error(sftp 连接已关闭); } if (sftp.getSession() ! null) { sftp.getSession().disconnect(); } } } catch (JSchException e) { log.error(sftp 断开连接失败原因{}, e.getMessage(), e); } } }外部调用upPath需要传输的路径file是当前文件sftpUtils.upload(upPath, file);