常用SFTP工具类(多个公用方法)
欢迎访问个人博客 德鲁大叔撸代码
SFTP工具类:
/*** @ClassName SftpUtils* @Description sftp工具类* @Author tengxiao.ma* @Date 2020/3/20 11:08**/
@Component
@Slf4j
public class SftpUtils {private static ChannelSftp sftp = null;private static Session sshSession = null;}
具体的方法如下:
一 :连接SFTP服务器方法
public ChannelSftp connect() {String sftpPwd = PyxisConfig.getInstance().getProperty(Constants.SFTP_PWD); //密码String sftpHost = PyxisConfig.getInstance().getProperty(Constants.SFTP_HOST); //ipint port = Integer.valueOf(PyxisConfig.getInstance().getProperty(Constants.SFTP_PORT)); //端口号String sftpUser = PyxisConfig.getInstance().getProperty(Constants.SFTP_USER); //用户名try {JSch jsch = new JSch();jsch.getSession(sftpUser, sftpHost, port);sshSession = jsch.getSession(sftpUser, sftpHost, port);sshSession.setPassword(sftpPwd);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect(30000);Channel channel = sshSession.openChannel("sftp");channel.connect(10000);sftp = (ChannelSftp) channel;log.info("连接SFTP服务器{}成功",sftpHost);return sftp;} catch (Exception e) {log.info("连接SFTP服务器{}失败,对账异常结束{}",sftpHost,e);return null;}}
二:一些公共的方法
1 判断文件夹是否存在
public static boolean isDirExist(String directory) {boolean isDirExistFlag = false;try {//lstat()检索文件或目录的文件属性SftpATTRS sftpATTRS = sftp.lstat(directory);isDirExistFlag = true;//isDir()检查此文件是否为目录return sftpATTRS.isDir();} catch (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isDirExistFlag = false;}}return isDirExistFlag;}
2 创建目录
public static boolean createDir(String createpath) {try {if (isDirExist(createpath)) {sftp.cd(createpath);return true;}String pathArry[] = createpath.split("/");StringBuffer filePath = new StringBuffer("/");for (String path : pathArry) {if (path.equals("")) {continue;}filePath.append(path + "/");if (isDirExist(filePath.toString())) {sftp.cd(filePath.toString());} else {sftp.mkdir(filePath.toString());sftp.cd(filePath.toString());}}sftp.cd(createpath);return true;} catch (SftpException e) {e.printStackTrace();}return false;}
3 删除文件
public static boolean deleteFile(String filePath) {File file = new File(filePath);if (!file.exists()) {return false;}if (!file.isFile()) {return false;}boolean rs = file.delete();return rs;}
4 关闭sftp连接
public static void disconnect() {if (sftp != null) {if (sftp.isConnected()) {sftp.disconnect();}}if (sshSession != null) {if (sshSession.isConnected()) {sshSession.disconnect();}}}
5 删除stfp文件
/*** 删除stfp文件* @param directory:要删除文件所在目录* @param deleteFile:要删除的文件*/public static void deleteSFTP(String directory, String deleteFile) {try {sftp.rm(directory + deleteFile);} catch (Exception e) {log.info("删除SFTP文件失败");}}
三、单个文件上传
/*** 上传单个文件* @param remotePath:远程保存目录* @param remoteFileName:保存文件名* @param localPath:本地上传目录(以路径符号结束)* @param localFileName:上传的文件名* @return*/public static boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName){FileInputStream in = null;try {createDir(remotePath);File file = new File(localPath + localFileName);in = new FileInputStream(file);sftp.put(in, remoteFileName);return true;}catch (FileNotFoundException e){e.printStackTrace();}catch (SftpException e){e.printStackTrace();}finally{if (in != null){try{in.close();}catch (IOException e){e.printStackTrace();}}}return false;}
四、单个文件下载
/*** 下载单个文件* @param directory 下载目录(远程文件所在目录)* @param downloadFile 下载的文件名* @param saveFile 结束文件的全路径* @param sftp*/public static void download(String directory, String downloadFile,String saveFile, ChannelSftp sftp) {try {sftp.cd(directory);sftp.get(downloadFile,saveFile);}catch (Exception e){log.info("下载sftp文件失败");}}/*** 下载单个文件* @param remotePath:远程下载目录(以路径符号结束)* @param remoteFileName:下载文件名* @param localPath:本地保存目录(以路径符号结束)* @param localFileName:保存文件名* @return*/public static boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {FileOutputStream fieloutput = null;try {File file = new File(localPath + localFileName);fieloutput = new FileOutputStream(file);sftp.get(remotePath + remoteFileName, fieloutput);return true;} catch (FileNotFoundException e) {e.printStackTrace();} catch (SftpException e) {e.printStackTrace();} finally {if (null != fieloutput) {try {fieloutput.close();} catch (IOException e) {e.printStackTrace();}}}return false;}
五、批量上传文件
/*** 批量上传文件* @param remotePath 远程地址* @param localPath 本地文件路径* @param del* @return*/public static boolean bacthUploadFile(String remotePath, String localPath,boolean del) {try {File file = new File(localPath);File[] files = file.listFiles();for (int i = 0; i < files.length; i++) {if (files[i].isFile()&& files[i].getName().indexOf("bak") == -1) {if (uploadFile(remotePath, files[i].getName(),localPath, files[i].getName())&& del) {//上传后删除本地文件deleteFile(localPath + files[i].getName());}}}return true;} catch (Exception e) {e.printStackTrace();} finally {disconnect();}return false;}
六、批量文件下载
/*** 批量下载文件* @param remotePath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)* @param fileEndFormat:下载文件格式(文件格式)* @param del:下载后是否删除sftp文件* @return*/public static List<String> batchDownLoadFile(String remotePath, String localPath,String fileFormat, String fileEndFormat, boolean del) {List<String> filenames = new ArrayList<String>();try {Vector v = sftp.ls(remotePath); //lstat(String path):列出远程目录的内容if (v.size() > 0) {System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());Iterator it = v.iterator();while (it.hasNext()) {ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();String filename = entry.getFilename();SftpATTRS attrs = entry.getAttrs();if (!attrs.isDir()) {boolean flag = false;String localFileName = localPath + filename;fileFormat = fileFormat == null ? "" : fileFormat.trim();fileEndFormat = fileEndFormat == null ? "": fileEndFormat.trim();// 三种情况if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {if (filename.startsWith(fileFormat)) {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {if (filename.endsWith(fileEndFormat)) {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}} else {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}}}}} catch (SftpException e) {e.printStackTrace();} finally {}return filenames;}
常用SFTP工具类(多个公用方法)相关推荐
- java中常用的工具类
1. 常用零散工具类 1.1[DateUtil.java]日期处理的工具类 /*** 时间日期处理工具* String -> Date* Date -> String* 以及生成含有日期的 ...
- Android项目中常用的工具类集(史上最全整理)
如果你是一名有经验的Android开发者,那么你一定积累了不少的工具类,这些工具类是帮助我们快速开发的基础.如果你是新手,那么有了这些辅助类,可以让你的项目做起来更加的简单. 下面介绍一个在GitHu ...
- Android常用的工具类
2019独角兽企业重金招聘Python工程师标准>>> 最新最准确内容建议直接访问原文:Android常用的工具类 主要介绍总结的Android开发中常用的工具类,大部分同样适用于J ...
- 常用并发工具类(锁和线程间通信工具类)
常用并发工具类总结 JUC 下的常用并发工具类(锁和线程间通信工具类),主要包括 ReentrantLock.ReentrantReadWriteLock.CountDownLatch.CyclicB ...
- java并发编程中常用的工具类 Executor
/*************************************************** * TODO: description . * @author: gao_chun * ...
- java常用工具类和Hutool常用的工具类整理
java常用工具类和Hutool常用的工具类整理 1.java常用工具类 1.1 Scanner类 /*** Scanner 类*/@Testpublic void testScanner() {Sc ...
- Vue-一些常用的工具类
本文介绍一些常用的工具类 1.验证码 如下图,一般的后台管理系统都会在登录的时候设计一个验证码,这个验证码是前端生成的,点击canvas可以切换验证码.二维码的类型是数字或者字母自己可以根据需要设置, ...
- java web 项目 常用 小工具类 ~~~~
java web 项目 常用 小工具类 ~~~~ 一 .DateUtil 日期工具类 package com.devframe.common.util;import java.text.Simple ...
- Android常用的工具类汇总(方便日后使用)
平时进行android开发时候,可能需要使用各种各样的工具类,每次总要去上网搜索,费时费力,因此特此将其整理发出来,小伙伴可自行收藏. 1.LogUtils工具类 /*** 控制Log开关的工具类*/ ...
- 常用JSON工具类JsonUtil封装
前言 项目中经常会有String转Object以及Object转Json字符串的需求,故封装一个常用Json工具类 Maven依赖 <dependency><groupId>o ...
最新文章
- 为计算机编程序英语作文,计算机编程员英文简历范文
- Nature综述:真菌的多样性:真菌的高通量测序及鉴定
- SQL SERVER 存储过程执行带输出参数的SQL语句拼接
- html中加盒子,在HTML中各类型盒子的基线应如何确定
- centos配置occi环境变量_拓展学习-golang的下载、安装和环境配置教程
- 让vs2008支持jQuery的智能提示!
- (90)FPGA仿真计数器激励
- VUE图片预览放大缩小插件viewer
- 通过IO流下载Excel文件
- go语言中关于文件的操作+工作目录的拼接
- 拓端tecdat|R语言隐马尔可夫模型HMM识别股市变化分析报告
- php单引号的作用,PHP中单引号和双引号的区别与作用
- Win10屏幕截图无法使用怎么回事
- 融资1350万美元,待开启的元宇宙·数字人
- day27-迭代器协议,协程,同步异步
- visio2007 uml模板包
- 2021年化工自动化控制仪表考试报名及化工自动化控制仪表新版试题
- 如何取消IE“已限制此网页运行可以访问计算机的脚本或ActiveX控件”
- win7旗舰版64位下完美安装和破解loadrunner11
- 【RTS】安海波老师:SIP与RTC融合分享笔记