Java FTP操作工具类

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java FTP操作工具类

洛阳泰山   2022-06-03 我要评论

前言

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

windows服务器搭建FTP服务

打开控制版面,图示win 10为例。

点击程序

选择 启用或者关闭Windows 功能

勾选启用 Internet Information Services 下FTP相关服务和 IIS 管理控制平台还有万维网服务 后,点击确定。

打开 IIS管理器

选中网站,鼠标右键 ,添加 FTP 站点

添加 网站名称,选择本地物理路径 ,设置完毕,点击。

填写自己的内网ip,选择 无 SSL,点击下一步。

勾选匿名 (访问时候不需要账户密码验证),允许所有用户 ,选择 读取 和写入权限(根据自己需求选择),点击完成。

同一内网的任何电脑的文件夹 内输入 自己设置的ip和端口  ftp://ip:port ,即可访问。

工具类方法

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

代码展示

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");
 
    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们