SftpClient.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package sys.sc.opplugin.utils;
  2. /**
  3. * @author cjz
  4. * @date 2024/9/9 17:05
  5. * @description:连接服务器获取sftp,工具类
  6. */
  7. import com.jcraft.jsch.ChannelSftp;
  8. import com.jcraft.jsch.JSch;
  9. import com.jcraft.jsch.Session;
  10. import com.jcraft.jsch.SftpException;
  11. import java.io.FileOutputStream;
  12. import java.io.InputStream;
  13. public class SftpClient {
  14. private String host;
  15. private String usernmae;
  16. private String password;
  17. private int port;
  18. private Session session;
  19. private ChannelSftp sftpChannel;
  20. public SftpClient(String host, String user, String password,int port) {
  21. this.host = host;
  22. this.usernmae = user;
  23. this.password = password;
  24. this.port=port;
  25. }
  26. // 连接到 SFTP 服务器
  27. public void connect() throws Exception {
  28. JSch jsch = new JSch();
  29. session = jsch.getSession(usernmae, host, port);
  30. session.setPassword(password);
  31. session.setConfig("StrictHostKeyChecking", "no");
  32. session.connect();
  33. sftpChannel = (ChannelSftp) session.openChannel("sftp");
  34. sftpChannel.connect();
  35. }
  36. //根据服务器路径读取文件,返回文件流
  37. public InputStream fileInputStream(String remoteFilePath) throws SftpException {
  38. InputStream inputStream = sftpChannel.get(remoteFilePath);
  39. return inputStream;
  40. }
  41. //上传文件到服务器路径,
  42. public void fileCreat(String localFilePath,String remoteFilePath) throws SftpException {
  43. //本地服务器传到服务器文件
  44. sftpChannel.put(localFilePath,remoteFilePath);
  45. }
  46. // 断开连接
  47. public void disconnect() {
  48. if (sftpChannel != null && sftpChannel.isConnected()) {
  49. sftpChannel.disconnect();
  50. }
  51. if (session != null && session.isConnected()) {
  52. session.disconnect();
  53. }
  54. }
  55. public ChannelSftp getSftpChannel() {
  56. return sftpChannel;
  57. }
  58. }