前言

网上百度了很多FTP的java 工具类,发现文章代码都比较久远,且代码臃肿,即使搜到了代码写的还可以的,封装的常用操作方法不全面,于是自己花了半天实现一个好用的工具类。最初想用java自带的FTPClient 的jar 去封装,后来和apache的jar工具包对比后,发现易用性远不如apache,于是决定采用apache的ftp的jar 封装ftp操作类。

之前写过一篇  windows 服务器搭建FTP服务的教程

点击查看

工具类方法

  • 账户密码登录方法
  • 无账号密码登录方法
  • 字符转码方法
  • 判断文件目录是否存在方法
  • 获取文件列表方法
  • 上传文件方法
  • 下载文件方法
  • 上传文件夹方法
  • 下载文件夹方法
  • 删除文件方法
  • 删除文件夹方法
  • 创建文件夹方法
  • 文件重命名方法

代码展示

pom文件引入依赖关系 commons-net jar

        <!-- https://mvnrepository.com/artifact/commons-net/commons-net --><dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.6</version></dependency>

工具类完整代码


import org.apache.commons.net.ftp.*;import java.io.*;
import java.util.ArrayList;
import java.util.List;/*** Java FTP工具类*/
public class FTPUtil {private static FTPClient ftp;/*** 方法描述:  转码*/private static String transcode(String text){try {return new String(text.getBytes("GBK"),FTP.DEFAULT_CONTROL_ENCODING);} catch (UnsupportedEncodingException e) {return null;}}/*** 方法描述: 连接 ftp服务器 匿名登录无密码*/public static void connectServer(String ip, int port) throws IOException {connectServer(ip,port,"anonymous",null);}/*** 方法描述: 连接 ftp服务器*/public static void connectServer(String ip, int port, String user, String password) throws IOException {// 连接ftp服务器ftp = new FTPClient();ftp.connect(ip, port);// 登录ftp服务器ftp.login(user, password);//设置编码ftp.setControlEncoding("GBK");//设置文件类型ftp.setFileType(FTP.BINARY_FILE_TYPE);}/*** 关闭连接*/public static void closeServer() throws IOException {if (ftp.isConnected()) {ftp.logout();ftp.disconnect();}}/*** 判断目录是否存在*/public static boolean existDirectory(String pathname) throws IOException {boolean flag = false;FTPFile[] ftpFileArr = ftp.listFiles(pathname);for (FTPFile ftpFile : ftpFileArr) {if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(pathname)) {flag = true;break;}}return flag;}/** 获取文件列表*/public static List<String> listFiles(String path) throws IOException {FTPFile[] ftpFiles = ftp.listFiles(path);List<String> retList = new ArrayList<String>();for (FTPFile ftpFile : ftpFiles) {retList.add(ftpFile.getName());}return retList;}/*** 上传文件*/public static boolean uploadFile(String remote,String local) throws IOException {InputStream is=new FileInputStream(local);return ftp.storeFile(transcode(remote),is);}/*** 下载文件*/public static boolean downloadFile(String remote,String local) throws IOException {OutputStream out=new FileOutputStream(local);return ftp.retrieveFile(transcode(remote),out);}/*** 删除文件*/public static boolean deleteFile(String remote) throws IOException {return ftp.deleteFile(transcode(remote));}/*** 删除文件夹*/public static void deleteFolder(String remote) throws IOException {FTPFile[] ftpFiles=ftp.listFiles(transcode(remote));for (FTPFile ftpFile : ftpFiles) {if(ftpFile.isDirectory()){deleteFolder(remote+"/"+ftpFile.getName());ftp.removeDirectory(transcode(remote+"/"+ftpFile.getName()));}else{deleteFile(ftpFile.getName());}}ftp.removeDirectory(transcode(remote));}/*** 上传文件夹到ftp服务器*/public static void uploadFolder(String remote,String local) throws IOException {File localFile=new File(local);if(localFile.isDirectory()){String remoteDir=remote+"/"+localFile.getName();makeDirectory(remoteDir);File[] partFiles=localFile.listFiles();for (File file : partFiles) {if(file.isDirectory()){uploadFolder(remoteDir+"/"+file.getName(),local+"/"+file.getName());}else {uploadFile(remoteDir+"/"+file.getName(),local+"/"+file.getName());}}}}/*** 下载文件夹到本地*/public static void downloadFolder(String remote,String local) throws IOException {File localFile=new File(local);if(!localFile.exists()){localFile.mkdirs();}FTPFile[] ftpFiles=ftp.listFiles(transcode(remote));for (FTPFile ftpFile : ftpFiles) {if(ftpFile.isDirectory()){downloadFolder(remote+"/"+ftpFile.getName(),local+"/"+ftpFile.getName());}else {downloadFile(remote+"/"+ftpFile.getName(),local+"/"+ftpFile.getName());}}}/*** 创建文件夹*/public static void makeDirectory(String remote) throws IOException {if(remote.startsWith("/")){remote=remote.substring(1);}String[] dirNames = remote.split("/");String tempPath="";for (String dirName : dirNames) {tempPath=tempPath+"/"+dirName;ftp.makeDirectory(transcode(tempPath));}}/*** 重命名*/public static boolean rename(String from, String to) throws IOException {return  ftp.rename(transcode(from),transcode(to));}}

使用示例

    public static void main(String[] args) throws IOException {//匿名免密码登录FTPUtil.connectServer("172.16.10.201",19001,"anonymous",null);//下载ftp根目录所有文件到本地文件夹FTPUtil.downloadFolder("/","D://ftp");//删除文件夹以及文件FTPUtil.deleteFolder("tarzan");//创建文件夹FTPUtil.makeDirectory("tarzan/cms");//文件夹或文件重命名FTPUtil.rename("泰山","泰山123");//上传文件夹FTPUtil.uploadFolder("software","D:\\Git");}

手写一个好用的Java FTP操作工具类相关推荐

  1. 第二季:5公平锁/非公平锁/可重入锁/递归锁/自旋锁谈谈你的理解?请手写一个自旋锁【Java面试题】

    第二季:5值传递和引用传递[Java面试题] 前言 推荐 值传递 说明 题目 24 TransferValue醒脑小练习 第二季:5公平锁/非公平锁/可重入锁/递归锁/自旋锁谈谈你的理解?请手写一个自 ...

  2. Java 手写一个SQL分页

    Java手写一个类似PageHelper的分页SQL 目前分页插件众所周知的莫过于和mybatis完美融合的PageHelper了,简单两行代码就实现了sql分页,配合PageInfo类,将数据总数量 ...

  3. 用Java手写一个微型下载资源网站

    文章目录 手写一个微型下载资源网站[Java实现用户注册.登陆.下载功能] 一.技术栈 二.流程分析图 注册 登陆 下载 三.案例实现效果 首页 注册 登陆 下载网主页 壁纸下载 书籍下载 影视下载 ...

  4. 【干货】JDK动态代理的实现原理以及如何手写一个JDK动态代理

    动态代理 代理模式是设计模式中非常重要的一种类型,而设计模式又是编程中非常重要的知识点,特别是在业务系统的重构中,更是有举足轻重的地位.代理模式从类型上来说,可以分为静态代理和动态代理两种类型. 在解 ...

  5. 肝一波 ~ 手写一个简易版的Mybatis,带你深入领略它的魅力!

    零.准备工作 <dependencies><dependency><groupId>mysql</groupId><artifactId>m ...

  6. 硬核!手写一个优先队列

    文章收录在首发公众号:bigsai 期待你的到访! 前言 事情还要从一个故事讲起: 对于上面那只可爱的小狗狗不会,本篇即为该教程,首先,我要告诉这只可爱的小狗狗,这种问题你要使用的数据结构为优先队列, ...

  7. 从 0 开始手写一个 Spring MVC 框架,向高手进阶

    转载自   从 0 开始手写一个 Spring MVC 框架,向高手进阶 Spring框架对于Java后端程序员来说再熟悉不过了,以前只知道它用的反射实现的,但了解之后才知道有很多巧妙的设计在里面.如 ...

  8. @cacheable 设置过期时间_缓存面试三连击——聊聊Redis过期策略?内存淘汰机制?再手写一个LRU 吧!...

    大家好,今天我和大家想聊一聊有关redis的过期策略的话题. 听到这里你也许会觉得:"我去,我只是个日常搬砖的,这种偏底层的知识点,我需要care吗?" 话虽如此·,但是兄die, ...

  9. zookeeper springboot_摊牌了!我要手写一个“Spring Boot”

    ❝ 目前的话,已经把 Spring MVC 相关常用的注解比如@GetMapping .@PostMapping .@PathVariable 写完了.我也已经将项目开源出来了,地址:https:// ...

最新文章

  1. Qt通过ODBC读取excel文件
  2. 计算机控制的点火系统由,第八节(点火系统)
  3. BZOJ 3329: Xorequ(数位dp+递推)
  4. git ssh key生成
  5. 【ElasticSearch】Es 源码之 快照 RepositoriesModule RepositoriesService 源码解读
  6. python之__repr__
  7. 网页打印和ActiveX控件打印
  8. 值得收藏的几千T超多学习资源合集分享
  9. 解除windows10多账户远程桌面连接限制
  10. seafile专业版集成微软的office online实现在线协同编辑
  11. 苹果亮度自动调节怎么关闭_笔记本黑苹果系统亮度调节驱动
  12. “蓝凤凰”开网店,卖起了这么多高颜值又神奇的生物
  13. PageAdmin Cms如何实现信息的定时发布
  14. 嚼得菜根做得大事·《菜根谭》·十
  15. VIM源生linux代码编辑器使用
  16. 多线程爬取4k超高清美图壁纸
  17. 字符常量/字符变量 计算sizeof
  18. 电子健康卡(码)理解
  19. 【ios游戏开发】分享share
  20. css 流式布局 九宫格布局

热门文章

  1. java 复数的除法_Java中 如果复数类成员是int型,怎么实现两个复数相除
  2. 数仓模型设计时代理键的使用
  3. 一个高级金领的全套名牌装备
  4. 分布式架构-ZK分布式锁中死锁和羊群效应解决方案
  5. 天天模拟器显示获取服务器失败怎么回事,win7系统。用天天模拟器。获取虚拟机IP失败!!!!!!!!!!!!!...
  6. 导出FBX修改namespace
  7. 局域网中无法访问的解决方法 1
  8. 使用企业微信移动办公效果如何?
  9. 《iOS移动开发从入门到精通》图书连载一:如果你也想开发一款自己的APP,可以看一下这篇文
  10. Python爬虫基础--爬取王者荣耀英雄皮肤图片