Linux下Sftp上送文件时自动创建多级目录
linux-dash
A beautiful web dashboard for Linux
项目地址:https://gitcode.com/gh_mirrors/li/linux-dash

·
来自:
今天测试前一段时间写好的程序时出现这么个问题,Sftp上送文件时,可以上送成功,但是一直找不到那个目录,是个小问题,但是很头疼,细细的通过日志检测后发现,在分割目录那个地方有点问题。
附上代码:
/**
* 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
*
* @param basePath
* 服务器的基础路径
* @param directory
* 上传到该目录
* @param sftpFileName
* sftp端文件名
* @param input
* 输入流 throws SftpException
*/
public boolean upload(String directory, String sftpFileName,
InputStream input) {
boolean ret = false;
try {
// sftp.cd(basePath);
sftp.cd(directory);
ret = true;
} catch (SftpException e) {
Log4jBean.logger.error("对方目录可能不存在[" + directory + "],需要创建目录,异常信息为["
+ e.getMessage() + "]");
// 目录不存在,则创建文件夹
String[] dirs = directory.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath+="/"+dir;
//tempPath = dir;
try {
Log4jBean.logger.info("检测目录[" + tempPath + "]");
sftp.cd(tempPath);
ret = true;
} catch (SftpException ex) {
try {
Log4jBean.logger.error("创建目录[" + tempPath + "]");
sftp.mkdir(tempPath);
sftp.cd(tempPath);
Log4jBean.logger.error("进入目录[" + tempPath + "]");
ret = true;
} catch (SftpException e1) {
Log4jBean.logger.error("创建目录[" + tempPath
+ "]失败1,异常信息[" + e1.getMessage() + "]");
ret = false;
return ret;
} catch (Exception e1) {
Log4jBean.logger.error("创建目录[" + tempPath
+ "]失败2,异常信息[" + e1.getMessage() + "]");
ret = false;
return ret;
}
} catch (Exception e1) {
Log4jBean.logger.error("创建目录[" + tempPath + "]失败3,异常信息["
+ e1.getMessage() + "]");
ret = false;
return ret;
}
}
Log4jBean.logger.info("创建目录完成");
ret = true;
} catch (Exception e1) {
Log4jBean.logger.error("进入目录[" + directory + "]失败,异常信息["
+ e1.getMessage() + "]");
ret = false;
return ret;
}
try {
sftp.put(input, sftpFileName);// 上传文件
ret = true;
} catch (SftpException e) {
Log4jBean.logger.error("Sftp文件处理异常,异常信息为[" + e.getMessage() + "]");
ret = false;
}
return ret;
}
出错地方:
这个是之前没改的,检查目录为空后,直接退出循环,执行下面的程序,那么问题来了,在linux下,用一个不是超级管理员的用户连接上Sftp去上送文件时,碰到这个相对路径时,直接用循环判断每一层路径时,很容易造成空路径创建不成功,及会使文件放不到原有位置。因为你用"/"这个进行分割了,比如相对路径是file/Grgz/XXX.txt,分割完就会发现前面的file这个目录为空,导致没取上,但是如果你在file的前面加一个/的话,那样分割也不对噢,因为那样就会造成从更目录开始创建目录了。
所以最好的办法就是加上绝对路径,这样最保险,最好
如下是我的绝对路径获取方式(这个可以根据自己的实际情况来写绝对路径)
下面把之前判断目录为空直接退出的情况改为判空时就继续下一级目录的判断,这样就会一级一级的检查,那么就不会漏了。这个很重要
效果图:
这样的话,就会一级一级去检查并创建,很不错O(∩_∩)O哈哈~。




A beautiful web dashboard for Linux
最近提交(Master分支:6 个月前 )
186a802e
added ecosystem file for PM2 4 年前
5def40a3
Add host customization support for the NodeJS version 4 年前
更多推荐
所有评论(0)