1.SFtp 与Ftp 的区别:

简单来说,SFtp安全性高

2.SFtp工具类

import com.jcraft.jsch.*;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;public class SFtpUtils {Logger log = LoggerFactory.getLogger(SFtpUtils.class);private Session session = null;private ChannelSftp channel = null;//服务器ip地址public String host;//端口号public int port;//连接超时时间(单位:秒)private int timeout;//用户名public String username;//密码public String password;/*** SFTP 安全文件传送协议** @param host     SFTP服务器IP地址* @param port     SFTP服务器端口* @param timeout  连接超时时间,单位毫秒* @param username 用户名* @param password 密码*/public SFtpUtils(String host, int port, int timeout, String username, String password) {this.host = host;this.port = port;this.timeout = timeout;this.username = username;this.password = password;}/*** 登录sftp** @return*/public boolean login() {try {JSch jSch = new JSch();session = jSch.getSession(username, host, port);if (password != null) {session.setPassword(password);}Properties config = new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config);session.setTimeout(timeout);session.connect();channel = (ChannelSftp) session.openChannel("sftp");channel.connect();return true;} catch (Exception e) {log.error("sftp 服务器登录失败! " + e);return false;}}/*** 登出*/public void logout() {if (channel != null) {channel.quit();channel.disconnect();}if (session != null) {session.disconnect();}}/*** 上传文件** @param pathName 服务器目录* @param fileName 服务器上保存的文件名* @param is       输入文件流* @return*/public boolean uploadFile(String pathName, String fileName, InputStream is) {if (!changeDir(pathName)) {return false;}try {channel.put(is, fileName, ChannelSftp.OVERWRITE);if (!existFile(fileName)) {return false;}return true;} catch (SftpException e) {log.error("上传文件失败!", e);return false;} finally {//changeDir(currentDir());}}/*** 上传文件** @param pathName  服务器目录* @param fileName  服务器上保存的文件名* @param localFile 本地文件* @return*/public boolean uploadFile(String pathName, String fileName, String localFile) {if (!changeDir(pathName)) {log.error(pathName + "路径改变失败!");return false;}try {channel.put(localFile, fileName, ChannelSftp.OVERWRITE);if (!existFile(fileName)) {log.error(fileName + "文件不存在");return false;}return true;} catch (SftpException e) {log.error("上传文件失败!", e);return false;} finally {changeDir(currentDir());}}/*** 上传文件** @param dest      服务器上保存的路径* @param localFile 本地文件* @return*/public boolean uploadFile(String dest, String localFile) {try {channel.put(localFile, dest, ChannelSftp.OVERWRITE);return true;} catch (Exception e) {log.error("上传文件失败!", e);return false;} finally {changeDir(currentDir());}}public String[] lsGrep(String path) throws Exception {Vector<ChannelSftp.LsEntry> list = null;try {//ls方法会返回两个特殊的目录,当前目录(.)和父目录(..)list = channel.ls(path);} catch (SftpException e) {return new String[0];}List<String> resultList = new ArrayList<String>();for (ChannelSftp.LsEntry entry : list) {resultList.add(entry.getFilename());}return resultList.toArray(new String[0]);}/*** 下载文件** @param remotePath* @param fileName* @param localPath* @return*/public boolean downloadFile(String remotePath, String fileName, String localPath) {if (!changeDir(remotePath)) {return false;}String localFilePath = localPath + File.separator + fileName;try {channel.get(fileName, localFilePath);File localFile = new File(localFilePath);if (!localFile.exists()) {return false;}return true;} catch (SftpException e) {log.error("文件下载失败!", e);return false;} finally {changeDir(currentDir());}}/*** 得到区县反馈到省级sftp服务器上的报文** @param filePath:文件路径* @return*/public String getFkbwFileXml(String filePath) {String xmlResultStr = "";try {String read;InputStream inputStream = channel.get(filePath);BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));while ((read = bf.readLine()) != null) {xmlResultStr = xmlResultStr + read;}inputStream.close();} catch (Exception e) {e.printStackTrace();System.out.println("-----------------获取sftp服务器上报文出错--------------");}xmlResultStr = formatXml(xmlResultStr);return xmlResultStr;}public String formatXml(String unformattedXml) {try {final Document document = parseXmlFile(unformattedXml);OutputFormat format = new OutputFormat(document);format.setLineWidth(65);format.setIndenting(true);format.setIndent(2);Writer out = new StringWriter();XMLSerializer serializer = new XMLSerializer(out, format);serializer.serialize(document);return out.toString();} catch (IOException e) {throw new RuntimeException(e);}}private Document parseXmlFile(String in) {try {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();InputSource is = new InputSource(new StringReader(in));return db.parse(is);} catch (ParserConfigurationException e) {throw new RuntimeException(e);} catch (SAXException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}}/*** 删除文件夹** @param dirName 文件夹名* @return*/public boolean delDir(String dirName) {if (!changeDir(dirName)) {return false;}Vector<ChannelSftp.LsEntry> lsEntries = null;try {lsEntries = channel.ls(channel.pwd());} catch (SftpException e) {return false;}for (ChannelSftp.LsEntry lsEntry : lsEntries) {String fileName = lsEntry.getFilename();if (!fileName.equals(".") && !fileName.equals("..")) {if (lsEntry.getAttrs().isDir()) {delDir(fileName);} else {delFile(fileName);}}}if (!changeToParentDir()) {return false;}try {channel.rmdir(dirName);return true;} catch (SftpException e) {log.error("删除文件夹失败!", e);return false;}}/*** 删除文件** @param fileName* @return*/public boolean delFile(String fileName) {if (fileName == null || fileName.trim().equals("")) {return false;}try {channel.rm(fileName);return true;} catch (SftpException e) {log.error("删除文件失败!", e);return false;}}/*** 创建目录** @param dirName* @return*/public boolean makeDir(String dirName) {try {channel.mkdir(dirName);return true;} catch (SftpException e) {log.error("创建目录失败!", e);return false;}}/*** 当前工作目录** @return*/public String currentDir() {try {return channel.pwd();} catch (SftpException e) {log.error("当前工作目录失败!", e);return homeDir();}}/*** 根目录** @return*/public String homeDir() {try {return channel.getHome();} catch (SftpException e) {return "/";}}/*** 切换工作目录** @param pathName 路径* @return*/public boolean changeDir(String pathName) {if (pathName == null || pathName.trim().equals("")) {return false;}try {channel.cd(pathName.replaceAll("\\\\", "/"));return true;} catch (SftpException e) {log.error("改变路径失败!", e);return false;}}/*** 切换到上一级目录** @return*/public boolean changeToParentDir() {return changeDir("..");}/*** 切换到根目录** @return*/public boolean changetoHomeDir() {String homeDir = null;try {homeDir = channel.getHome();} catch (SftpException e) {return false;}return changeDir(homeDir);}/*** 当前目录是否存在问价夹或文件** @param name* @return*/public boolean exist(String name) {return exist(ls(), name);}/*** 指定目录是否存在问价夹或文件** @param name* @param path* @return*/public boolean exist(String path, String name) {return exist(ls(path), name);}/*** 当前目录是否存在文件** @param name* @return*/public boolean existFile(String name) {return exist(lsFiles(), name);}/*** 指定目录下是否存在文件** @param path 目录* @param name 文件* @return*/public boolean existFile(String path, String name) {return exist(lsFiles(path), name);}/*** 当前目录是否存在文件夹** @param name* @return*/public boolean existDir(String name) {return exist(lsDirs(), name);}/*** 指定目录下是否存在文件** @param path 目录* @param name 文件* @return*/public boolean existDir(String path, String name) {return exist(lsDirs(path), name);}/*** 当前目录下文件名称列表** @return String[]*/public String[] lsFiles() {return list(Filter.FILE);}/*** 指定目录下文件名称列表** @param pathName* @return*/public String[] lsFiles(String pathName) {String currentDir = currentDir();if (!changeDir(pathName)) {return new String[0];}String[] result = list(Filter.FILE);if (!changeDir(currentDir)) {return new String[0];}return result;}/*** 当前目录下文件夹名称列表*/public String[] lsDirs() {return list(Filter.DIR);}/*** 指定目录下文件夹名称列表*/public String[] lsDirs(String pathName) {if (!changeDir(pathName)) {return new String[0];}String[] result = list(Filter.DIR);if (!changeDir(currentDir())) {return new String[0];}return result;}/*** 当前目录下文件夹及文件名称列表** @return*/public String[] ls() {return list(Filter.ALL);}/*** 指定目录下文件夹及文件名称列表** @param pathName* @return*/public String[] ls(String pathName) {String currentDir = currentDir();if (!changeDir(pathName)) {return new String[0];}String[] result = list(Filter.ALL);if (!changeDir(currentDir)) {return new String[0];}return result;}/*** 列出当前目录下的文件及文件夹** @param filter* @return*/@SuppressWarnings("unchecked")public String[] list(Filter filter) {Vector<ChannelSftp.LsEntry> list = null;try {//ls方法会返回两个特殊的目录,当前目录(.)和父目录(..)list = channel.ls(channel.pwd());} catch (SftpException e) {return new String[0];}List<String> resultList = new ArrayList<String>();for (ChannelSftp.LsEntry entry : list) {if (filter(entry, filter)) {resultList.add(entry.getFilename());}}return resultList.toArray(new String[0]);}/*** 判断是否是过滤条件** @param filter* @return*/private boolean filter(ChannelSftp.LsEntry lsEntry, Filter filter) {String fileName = lsEntry.getFilename();if (filter.equals(Filter.ALL)) {return !fileName.equals(".") && !fileName.equals("..");} else if (filter.equals(Filter.FILE)) {return !fileName.equals(".") && !fileName.equals("..") && !lsEntry.getAttrs().isDir();} else if (filter.equals(Filter.DIR)) {return !fileName.equals(".") && !fileName.equals("..") && lsEntry.getAttrs().isDir();}return false;}/*** 枚举 用于过滤文件及文件夹*/public enum Filter {ALL, //文件及文件夹FILE, //文件DIR //文件夹}/*** 判断字符串是否存在数组中** @param strArr* @param str* @return*/private boolean exist(String[] strArr, String str) {if (strArr == null || strArr.length == 0) {return false;}if (str == null || str.trim().equals("")) {return true;}for (String s : strArr) {if (s.equals(str)) {return true;}}return false;}public boolean rename(String oldPath, String newPath) {try {channel.rename(oldPath, newPath);return true;} catch (SftpException e) {return false;}}/*** 获取文件** @param path* @return* @throws Exception*/public InputStream getFile(String path) throws Exception {return channel.get(path);}/*** 获取文件字节** @param filePath* @return* @throws Exception*/public byte[] getBytes(String filePath) throws Exception {InputStream is = channel.get(filePath);byte[] bizBuffer = new byte[(int) getFileSize(filePath)];byte[] bizBuf = new byte[1024];int bizN = 0;int bizIndex = 0;while ((bizN = is.read(bizBuf)) != -1) {System.arraycopy(bizBuf, 0, bizBuffer, bizIndex, bizN);bizIndex += bizN;}return bizBuffer;}/*** 获取文件大小** @param path* @return* @throws Exception*/public long getFileSize(String path) throws Exception {return channel.stat(path).getSize();}/*** 获取文件属性** @param path* @return* @throws Exception*/public SftpATTRS getFileAttrs(String path) throws Exception {return channel.lstat(path);}/*** 设置文件修改时间** @param path* @throws Exception*/public void setMtime(String path, int mtime) throws Exception {channel.setMtime(path, mtime);}}

3.使用

  //设置SFTP连接相关参数SFtpUtils sFtpUtils = new SFtpUtils(ip,Integer.parseInt(port),Integer.parseInt(timeout),username,password);//登录SFtpsFtpUtils.login();//调用相关方法sFtp.方法名//登出SFtpsFtpUtils.logout();

超详细的SFtp工具类及使用相关推荐

  1. java连接sftp工具类

    本工具类支持远程连接sftp,上传下载文件 需要用到是jar是jsch-0.1.29.jar import java.io.BufferedReader;import java.io.File;imp ...

  2. 基于java的SFTP工具类

    如果是FTP的看这里, 基于java的批量上传下载的FTP工具类 首先引入依赖 <dependency><groupId>org.netbeans.external</g ...

  3. 较详细的MongDB工具类

    最近在使用MongoDB这个数据库,总结了有个比较全的工具类,该类是针对MongoDB封装的一个CRUD的工具类, 可以满足常规的数据查询, 数据写入, 数据修改, 数据删除操作. 刚接触MongoD ...

  4. 墨者学院布尔盲注(超详细手工和工具)

    墨者学院的在线靶场中sql注入漏洞测试(布尔盲注),因为不管是时间盲注还是布尔盲注手工的话都需要大量的经历和时间来完成,正好自己最近在学习sql注入的盲注,就决定用手工做一次盲注的测试,以便于对sql ...

  5. Java基础18-String类【String类的特点对象个数常用方法】【超详细讲解】

    Java基础-String类[超详细讲解] String类的特点 String在java.lang.String包中 1:特点 (1)String类型不能被继承,因为由final修饰 (2)Strin ...

  6. JAVA常用工具类(实用高效)

    JAVA常用工具类(根据GITHUB代码统计) 从Google你能搜索到大量的关于Struts,Spring,Hibernate,iBatis等比较大的框架的资料,但是很少有人去关注一些小的工具包,但 ...

  7. (6)常用的Java工具类

    目录 前言: 第一部分:常用的16个工具类 一.org.apache.commons.io.IOUtils 二.org.apache.commons.io.FileUtils 三.org.apache ...

  8. 入门kpi的后台工具类

    1. 需求分析: 计算kpi 的过程中,会遇到很多 数量和比率的计算,而且很多的数值都是由固定的sql语句得来,所以就需要根据前端传入的kpi名字,拿出相应的  语句,计算方式,同时还要考虑相同的筛选 ...

  9. java超详细小程序对接微信支付(二),看完不会你打我

    4.支付通知回调 B-验证签名 因为这个接口是微信进行回调的,但是如果别人知道了这个接口就给进行伪造信息进行调用这个接口 补充一点,这里这个接口最后要返回给微信success 不然会一直进行调用该接口 ...

  10. Java二维码工具类(超详细注释)

    二维码工具类 准备工作: pom.xml 引入依赖 <!-- 二维码 --> <dependency><groupId>com.google.zxing</g ...

最新文章

  1. 还原黑客电影中那些Hacking技术的真相
  2. WPF QuickStart系列之样式和模板(Style and Template)
  3. 同等学力计算机综合难吗,报考2018年同等学力申硕计算机在职研究生毕业很困难吗...
  4. Kaggle机器学习入门实战 -- Titanic乘客生还预测
  5. erc20 php,使用php将erc20令牌从一个帐户传输到另一个帐户
  6. 从零开始netty学习笔记之BIO
  7. Eclipse 默认设置的换行长度
  8. docker for mac的JSON配置文件中的hosts项修改后无法生效
  9. CSS快速学习6:vertical-align讲解
  10. 09-R中文文本分析方便工具包chinese.misc简介
  11. WebDriver Selenium eclipse环境搭建
  12. 虚拟化部署ESXI6.7+intel x710-da4万兆网卡
  13. 打印机扫描到计算机,打印机扫描文件到电脑方法教程
  14. 微信支付--商家转账到零钱
  15. 不想学习的小颓靡怎么解决
  16. unity steamworksdk简单接入
  17. Windows服务器更改远程端口3389
  18. android 格式工厂,格式工厂app下载-格式工厂app安卓版下载[辅助工具]-华军软件园...
  19. 浏览器最小字体为12px以及解决方法
  20. python摄像头识别条形码、二维码并打印信息

热门文章

  1. mysql number 类型_MySQL 数据类型(转)
  2. 重装系统——Win10系统U盘启动盘制作教程(MSDN自带纯净版)
  3. 四川省大学生计算机作品大赛,我院承办2019“新华三杯”四川省大学生计算机作品大赛并获佳绩...
  4. 解锁WPS企业版,去广告,享会员服务
  5. java框架有哪几种,java权限框架有几种?常见的权限框架分享
  6. 蓝桥杯单片机历年真题答案
  7. L298N模块驱动电机(实现pwm调速)
  8. 勇者游戏C语言,c语言命令行-勇者斗恶龙
  9. TestBench基本写法与语法详解
  10. (笔记)《游戏脚本高级编程》——第1章 脚本编程概论