本地上传文件到SFTP服务器
代码
需要知道sftp服务器的ip,端口,用户名,密码,上传服务器的文件路径。
方法参数为文件上一级目录和要上传的本地文件路径
public void uploadSftp(String dir, String localFile){
try {
//1.获取会话
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();
//2.获取上传通道
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
//3.上传文件
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);
}
}
/**
* 判断目录是否存在
* @param directory
* @return
*/
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