FTP和SFTP的工具类

2024-06-14 10:48
文章标签 工具 ftp sftp

本文主要是介绍FTP和SFTP的工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

<dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.6</version>
</dependency>@Slf4j
public class FTPUtils {/*** 连接,如果失败重试3次,间隔1s** @param server* @return*/public static FTPClient connectFtp(FTPServer server) {FTPClient ftpClient = new FTPClient();ftpClient.setControlEncoding(server.getEncoding());for (int i = 0; i < 3; i++) {try {log.info("connecting...ftp服务器:" + server.getIp() + ":" + server.getPort());ftpClient.connect(server.getIp(), server.getPort()); //连接ftp服务器ftpClient.login(server.getAccount(), server.getPwd()); //登录ftp服务器int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器if (FTPReply.isPositiveCompletion(replyCode)) {log.info("连接成功...ftp服务器" + server.getIp() + ":" + server.getPort());break;}Thread.sleep(1000);log.info("连接失败...ftp服务器" + server.getIp() + ":" + server.getPort());} catch (Exception e) {log.error(e.getMessage(), e);}}return ftpClient;}/*** 下载文件 *** @param pathname  FTP服务器文件目录 ** @param filename  文件名称 ** @param localpath 下载后的文件路径 ** @return*/public static boolean downloadFile(FTPClient ftpClient, String pathname, String filename, String localpath) {OutputStream os = null;try {log.info("开始下载文件");ftpClient.enterLocalPassiveMode();//切换FTP目录ftpClient.changeWorkingDirectory(pathname);FTPFile[] ftpFiles = ftpClient.listFiles();for (FTPFile file : ftpFiles) {if (filename.equalsIgnoreCase(file.getName())) {File localFile = new File(localpath + file.getName());os = new FileOutputStream(localFile);ftpClient.setFileType(FTP.BINARY_FILE_TYPE);boolean flag = ftpClient.retrieveFile(file.getName(), os);if (!flag) {log.info("下载文件失败:" + file.getName());return false;} else {log.info("下载文件成功" + file.getName());}}}} catch (Exception e) {log.info("下载文件失败" + e.getMessage(), e);return false;} finally {if (os != null) {try {os.close();} catch (IOException e) {}}}return true;}/*** 删除文件 *** @param filename 要删除的文件名称 ** @return*/public static boolean deleteFile(FTPClient ftpClient, String filename, String pathname) {try {ftpClient.enterLocalPassiveMode();ftpClient.changeWorkingDirectory(pathname);log.info("开始删除文件");boolean flag = ftpClient.deleteFile(pathname + filename);log.info("删除文件成功");return flag;} catch (Exception e) {log.error("删除文件失败", e);return false;}}/*** 递归遍历出目录下面所有文件** @param pathName 需要遍历的目录,必须以"/"开始和结束* @throws IOException*/public static void list(FTPClient ftpClient, String pathName, List<String> arFiles) throws IOException {ftpClient.enterLocalPassiveMode();if (pathName.startsWith("/") && pathName.endsWith("/")) {String directory = pathName;//更换目录到当前目录ftpClient.changeWorkingDirectory(directory);FTPFile[] files = ftpClient.listFiles();for (FTPFile file : files) {if (file.isFile()) {arFiles.add(directory + file.getName());} else if (file.isDirectory()) {list(ftpClient, directory + file.getName() + "/", arFiles);}}}}/*** 递归遍历目录下面指定的文件名** @param pathName 需要遍历的目录,必须以"/"开始和结束* @param ext      文件的扩展名* @throws IOException*/public static void list(FTPClient ftpClient, String pathName, String ext, List<String> arFiles) throws IOException {ftpClient.enterLocalPassiveMode();if (pathName.startsWith("/") && pathName.endsWith("/")) {String directory = pathName;//更换目录到当前目录ftpClient.changeWorkingDirectory(directory);FTPFile[] files = ftpClient.listFiles();for (FTPFile file : files) {if (file.isFile()) {if (file.getName().endsWith(ext)) {arFiles.add(file.getName());}} else if (file.isDirectory()) {list(ftpClient, directory + file.getName() + "/", ext, arFiles);}}}}/*** 上传文件** @param pathname       ftp服务保存地址* @param fileName       上传到ftp的文件名* @param originfilename 待上传文件的名称(绝对地址) ** @return*/public static boolean uploadFile(FTPClient ftpClient, String pathname, String fileName, String originfilename) {InputStream inputStream = null;try {log.info("开始上传文件");ftpClient.enterLocalPassiveMode();inputStream = new FileInputStream(new File(originfilename));ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);ftpClient.changeWorkingDirectory(pathname);ftpClient.storeFile(fileName, inputStream);log.info("上传文件成功");} catch (Exception e) {log.info("上传文件失败" + e.getMessage(), e);return false;} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {}}}return true;}/*** 上传文件** @param pathname    ftp服务保存地址 必须是绝对地址* @param fileName    上传到ftp的文件名* @param inputStream 输入文件流* @return*/public static boolean uploadFile(FTPClient ftpClient, String pathname, String fileName, InputStream inputStream) {try {log.info("开始上传文件:{}/{}",pathname,fileName);ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);ftpClient.changeWorkingDirectory(pathname);ftpClient.storeFile(fileName, inputStream);log.info("上传文件成功");} catch (Exception e) {log.info("上传文件失败:{}/{}" + e.getMessage(),pathname,fileName, e);return false;}return true;}//创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建public static boolean createDirectory(FTPClient ftpClient, String remote) throws IOException {boolean success = true;String directory = remote + "/";// 如果远程目录不存在,则递归创建远程服务器目录if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(directory)) {int start = 0;int end = 0;if (directory.startsWith("/")) {start = 1;} else {start = 0;}end = directory.indexOf("/", start);String path = "";String paths = "";while (true) {String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");path = path + "/" + subDirectory;if (!existFile(ftpClient, path)) {if (ftpClient.makeDirectory(subDirectory)) {ftpClient.changeWorkingDirectory(subDirectory);} else {log.info("创建目录[" + subDirectory + "]失败");ftpClient.changeWorkingDirectory(subDirectory);}} else {ftpClient.changeWorkingDirectory(subDirectory);}paths = paths + "/" + subDirectory;start = end + 1;end = directory.indexOf("/", start);// 检查所有目录是否创建完毕if (end <= start) {break;}}}return success;}//判断ftp服务器文件是否存在public static boolean existFile(FTPClient ftpClient, String path) {try {FTPFile[] ftpFileArr = ftpClient.listFiles(path);if (ftpFileArr != null && ftpFileArr.length > 0) {return false;}return false;} catch (Exception e) {return false;}}public static void close(FTPClient ftpClient) throws IOException {if (ftpClient == null) {return;}try {if (ftpClient.isConnected()) {ftpClient.logout();ftpClient.disconnect();}} catch (Exception e) {log.error(e.getMessage(), e);}}public static class FTPServer {private String ip;private Integer port;private String account;private String pwd;private String encoding;public FTPServer() {}public FTPServer(String ip, Integer port, String account, String pwd, String encoding) {this.ip = ip;this.port = port;this.account = account;this.pwd = pwd;this.encoding = encoding;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getEncoding() {return encoding;}public void setEncoding(String encoding) {this.encoding = encoding;}}
}
<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version>	
</dependency>@Slf4j
public class SFTPUtils {/*** 连接,如果失败重试3次,间隔1s** @param server* @return*/public static ChannelSftp connectFtp(SFTPServer server) {ChannelSftp sftp = null;for (int i = 0; i < 3; i++) {try {log.info("connecting...ftp服务器:" + server.getIp() + ":" + server.getPort());JSch jsch = new JSch();Session sshSession = jsch.getSession(server.getAccount(), server.getIp(), server.getPort());sshSession.setPassword(server.getPwd());Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect();Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;log.info("连接成功...ftp服务器" + server.getIp() + ":" + server.getPort());break;} catch (Exception e) {try {Thread.sleep(1000);log.info("连接失败...ftp服务器" + server.getIp() + ":" + server.getPort() + ":" + e.getMessage(), e);} catch (InterruptedException e1) {log.error(e.getMessage(), e);}}}return sftp;}/*** 下载文件 *** @param pathname  FTP服务器文件目录 ** @param filename  文件名称 ** @param localpath 下载后的文件路径 ** @return*/public static void downloadFile(ChannelSftp sftp, String pathname, String filename, String localpath) {if (StringUtils.isEmpty(pathname) || !pathname.endsWith("/")) {throw new IllegalArgumentException("path is not illegal:" + pathname);}try (FileOutputStream outputStream = new FileOutputStream(localpath)) {log.info("开始下载文件:{}", pathname + filename);sftp.cd(pathname);sftp.get(filename, outputStream);log.info("文件已下载至{}", localpath);} catch (Exception e) {log.error(e.getMessage(), e);}}/*** 删除文件 *** @param filename 要删除的文件名称 ** @return*/public static boolean deleteFile(ChannelSftp sftp, String filename, String pathname) {if (StringUtils.isEmpty(pathname) || !pathname.endsWith("/")) {throw new IllegalArgumentException("path is not illegal:" + pathname);}try {sftp.cd(pathname);sftp.rm(filename);log.info("已删除{}", pathname + filename);return true;} catch (Exception e) {log.error(e.getMessage(), e);}return false;}/*** 递归遍历出目录下面所有文件** @param pathName 需要遍历的目录,必须以"/"开始和结束* @throws IOException*/public static void list(ChannelSftp sftp, String pathName, List<String> arFiles) throws IOException {if (StringUtils.isEmpty(pathName) || !pathName.endsWith("/")) {return;}try {sftp.cd(pathName);Vector<String> files = sftp.ls("*");for (int i = 0; i < files.size(); i++) {Object obj = files.elementAt(i);if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) obj;if (!entry.getAttrs().isDir()) {String file = pathName + entry.getFilename();arFiles.add(file);} else {if (!entry.getFilename().equals(".") && !entry.getFilename().equals("..")) {String folder = pathName + entry.getFilename() + "/";arFiles.add(folder);list(sftp, folder, arFiles);}}}}} catch (Exception e) {log.error(e.getMessage(), e);}}/*** 递归遍历目录下面指定的文件名** @param pathName 需要遍历的目录,必须以"/"开始和结束* @param ext      文件的扩展名* @throws IOException*/public static void list(ChannelSftp sftp, String pathName, String ext, List<String> arFiles) throws IOException {if (StringUtils.isEmpty(pathName) || !pathName.endsWith("/")) {return;}try {sftp.cd(pathName);Vector<String> files = sftp.ls("*");for (int i = 0; i < files.size(); i++) {Object obj = files.elementAt(i);if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) obj;if (!entry.getAttrs().isDir()) {if (entry.getFilename().endsWith(ext)) {String file = pathName + entry.getFilename();arFiles.add(file);}} else {if (!entry.getFilename().equals(".") && !entry.getFilename().equals("..")) {String folder = pathName + entry.getFilename() + "/";arFiles.add(folder);list(sftp, folder, arFiles);}}}}} catch (Exception e) {log.error(e.getMessage(), e);}}/*** 上传文件** @param pathname       ftp服务保存地址* @param fileName       上传到ftp的文件名* @param originfilename 待上传文件的名称(绝对地址) ** @return*/public static boolean uploadFile(ChannelSftp sftp, String pathname, String fileName, String originfilename) {if (StringUtils.isEmpty(pathname) || !pathname.endsWith("/")) {throw new IllegalArgumentException("path is not illegal:" + pathname);}try (InputStream inputStream = new FileInputStream(new File(originfilename));) {sftp.cd(pathname);sftp.put(inputStream, fileName);  //上传文件log.info("上传文件成功:{},源文件:{}", pathname + fileName, originfilename);return true;} catch (Exception e) {log.info("上传文件失败:{}" + e.getMessage(), pathname + fileName, e);log.error(e.getMessage(), e);return false;}}/*** 上传文件** @param pathname    ftp服务保存地址 必须是绝对地址* @param fileName    上传到ftp的文件名* @param inputStream 输入文件流* @return*/public static boolean uploadFile(ChannelSftp sftp, String pathname, String fileName, InputStream inputStream) {if (StringUtils.isEmpty(pathname) || !pathname.endsWith("/")) {throw new IllegalArgumentException("path is not illegal:" + pathname);}try {sftp.cd(pathname);sftp.put(inputStream, fileName);  //上传文件log.info("上传文件成功:{}", pathname + fileName);} catch (Exception e) {log.info("上传文件失败:{}" + e.getMessage(), pathname + fileName, e);return false;}return true;}/*** 递归根据路径创建文件夹*/public static boolean createDirectory(ChannelSftp sftp, String remote) throws IOException {if (StringUtils.isEmpty(remote) || !remote.endsWith("/")) {throw new IllegalArgumentException("path is not illegal:" + remote);}try {if (!existFolder(sftp, remote)) {sftp.mkdir(remote);}log.info("创建目录成功:{}", remote);return true;} catch (Exception e) {log.error(e.getMessage(), e);}return false;}//判断ftp服务器文件是否存在public static boolean existFile(ChannelSftp sftp, String path) {if (StringUtils.isEmpty(path) || path.endsWith("/")) {throw new IllegalArgumentException("path is not illegal:" + path);}boolean isExist = false;try {SftpATTRS sftpATTRS = sftp.lstat(path);isExist = true;return !sftpATTRS.isDir();} catch (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isExist = false;}}return isExist;}public static boolean existFolder(ChannelSftp sftp, String path) {if (StringUtils.isEmpty(path) || !path.endsWith("/")) {throw new IllegalArgumentException("path is not illegal:" + path);}boolean isExist = false;try {SftpATTRS sftpATTRS = sftp.lstat(path);isExist = true;return sftpATTRS.isDir();} catch (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isExist = false;}}return isExist;}public static void close(ChannelSftp sftp) {if (sftp == null) {return;}try {sftp.disconnect();sftp.getSession().disconnect();log.info("ftp连接已关闭");} catch (JSchException e) {log.error(e.getMessage(), e);log.info("ftp连接关闭失败");}}public static class SFTPServer {private String ip;private Integer port;private String account;private String pwd;private String encoding;public SFTPServer() {}public SFTPServer(String ip, Integer port, String account, String pwd, String encoding) {this.ip = ip;this.port = port;this.account = account;this.pwd = pwd;this.encoding = encoding;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getEncoding() {return encoding;}public void setEncoding(String encoding) {this.encoding = encoding;}}
}

这篇关于FTP和SFTP的工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1060189

相关文章

MySql match against工具详细用法

《MySqlmatchagainst工具详细用法》在MySQL中,MATCH……AGAINST是全文索引(Full-Textindex)的查询语法,它允许你对文本进行高效的全文搜素,支持自然语言搜... 目录一、全文索引的基本概念二、创建全文索引三、自然语言搜索四、布尔搜索五、相关性排序六、全文索引的限制七

基于Java实现回调监听工具类

《基于Java实现回调监听工具类》这篇文章主要为大家详细介绍了如何基于Java实现一个回调监听工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录监听接口类 Listenable实际用法打印结果首先,会用到 函数式接口 Consumer, 通过这个可以解耦回调方法,下面先写一个

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

JS+HTML实现在线图片水印添加工具

《JS+HTML实现在线图片水印添加工具》在社交媒体和内容创作日益频繁的今天,如何保护原创内容、展示品牌身份成了一个不得不面对的问题,本文将实现一个完全基于HTML+CSS构建的现代化图片水印在线工具... 目录概述功能亮点使用方法技术解析延伸思考运行效果项目源码下载总结概述在社交媒体和内容创作日益频繁的

基于Python打造一个全能文本处理工具

《基于Python打造一个全能文本处理工具》:本文主要介绍一个基于Python+Tkinter开发的全功能本地化文本处理工具,它不仅具备基础的格式转换功能,更集成了中文特色处理等实用功能,有需要的... 目录1. 概述:当文本处理遇上python图形界面2. 功能全景图:六大核心模块解析3.运行效果4. 相

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

基于Python和MoviePy实现照片管理和视频合成工具

《基于Python和MoviePy实现照片管理和视频合成工具》在这篇博客中,我们将详细剖析一个基于Python的图形界面应用程序,该程序使用wxPython构建用户界面,并结合MoviePy、Pill... 目录引言项目概述代码结构分析1. 导入和依赖2. 主类:PhotoManager初始化方法:__in

使用Python自建轻量级的HTTP调试工具

《使用Python自建轻量级的HTTP调试工具》这篇文章主要为大家详细介绍了如何使用Python自建一个轻量级的HTTP调试工具,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下... 目录一、为什么需要自建工具二、核心功能设计三、技术选型四、分步实现五、进阶优化技巧六、使用示例七、性能对比八、扩展方向建

基于Python打造一个可视化FTP服务器

《基于Python打造一个可视化FTP服务器》在日常办公和团队协作中,文件共享是一个不可或缺的需求,所以本文将使用Python+Tkinter+pyftpdlib开发一款可视化FTP服务器,有需要的小... 目录1. 概述2. 功能介绍3. 如何使用4. 代码解析5. 运行效果6.相关源码7. 总结与展望1