生活随笔
收集整理的這篇文章主要介紹了
上传文件到sftp服务器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本地上傳文件到SFTP服務器
代碼
需要知道sftp服務器的ip,端口,用戶名,密碼,上傳服務器的文件路徑。
方法參數為文件上一級目錄和要上傳的本地文件路徑
public void uploadSftp(String dir
, String localFile
){try {JSch jSch
= new JSch();Session session
= jSch
.getSession(sftpUsername
, sftpAddress
, sftpPort
);session
.setPassword(sftpPassword
);Properties properties
= new Properties();properties
.put("StrictHostKeyChecking", "no");session
.setConfig(properties
);session
.connect();Channel channel
= session
.openChannel("sftp");channel
.connect();ChannelSftp sftp
= (ChannelSftp) channel
;FileInputStream inputStream
;try {try {sftp
.cd(sftpFileUrl
);} catch (SftpException e
) {logger
.error("切換目錄失敗");throw new RuntimeException(e
);}String dirPath
= sftpFileUrl
+ dir
;if (!isDirExist(dirPath
, sftp
)){sftp
.mkdir(dirPath
);}sftp
.cd(dirPath
);inputStream
= new FileInputStream(localFile
);sftp
.put(inputStream
, "data.json");} catch (Exception e
) {logger
.error("上傳文件失敗");throw new RuntimeException(e
);}sftp
.disconnect();inputStream
.close();channel
.disconnect();session
.disconnect();logger
.info("上傳sftp服務器成功");} catch (Exception e
) {logger
.error("上傳sftp服務器失敗");throw new RuntimeException(e
);}}public static boolean isDirExist(String directory
, ChannelSftp sftp
){boolean isDirExistFlag
= false;try{SftpATTRS sftpATTRS
= sftp
.lstat(directory
);isDirExistFlag
= true;return sftpATTRS
.isDir();}catch (Exception e
){if (e
.getMessage().toLowerCase().equals("no such file")){isDirExistFlag
= false;}}return isDirExistFlag
;}
參考鏈接
- https://blog.csdn.net/weixin_45031612/article/details/123513850
- https://www.csdn.net/tags/MtTaAg5sMzc3NTIxLWJsb2cO0O0O.html
總結
以上是生活随笔為你收集整理的上传文件到sftp服务器的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。