FTP下载文件工具类

本文详细介绍了FtpUtil工具类的使用,包括创建FTP对象、连接、切换目录、下载和上传文件等关键功能,通过实际案例展示了如何进行机房数据同步操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.FtpUtil 使用案例
// 创建FTP对象
FtpUtil ftp = new FtpUtil(ip, port, userName, password);
try {
    // 连接FTP
    ftp.connect();
    ftp.switchDirectory(roomPath, false);
    logger.info("机房数据同步任务FTP当前所在路径:[{}]", ftp.getHome());

    // 下载文件
    String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
    fileName = roomFilePrefix + dateStr + ".txt";
    boolean r2 = ftp.download(fileName, tmpPath);
    if (!r2) {
        logger.info("机房数据同步任务FTP文件下载失败!");
        throw new Exception("文件下载失败");
    } else {
        logger.info("机房数据同步任务FTP文件下载成功,开始解析文件!");
        List<JfInfo> jfInfoList = TransBeanUtils.resolverTxt(tmpPath + fileName, SyncJobEnum.JF_INFO);
        if (CollectionUtil.isNotEmpty(jfInfoList)) {
            this.handleJfInfo(jfInfoList);
        }
    }
} catch (Exception e) {
    logger.error(e.getMessage());
    throw e;
} finally {
    ftp.close();
}

2.FtpUtil工具类

package com.hx.platform.dxjfgl.base.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName FtpUtil
 * @Description TODO
 * @Author yuanguowei
 * @Date 2021/12/29:15:13
 * @Version 1.0
 */
public class FtpUtil {

    private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    private String Control_Encoding = "UTF-8";

    private FTPClient client = null;

    private String host = "";
    private int port = 21;
    private String user = "";
    private String password = "";
    private String ftpPath = "/";

    @SuppressWarnings("unused")
    private FtpUtil() {
    }

    public FtpUtil(String host, int port, String user, String pwd) {
        this.host = host;
        this.port = port;
        this.user = user;
        this.password = pwd;
    }

    /**
     * 获取当前FTP所在目录位置
     *
     * @return
     */
    public String getHome() {
        return this.ftpPath;
    }

    /**
     * 连接FTP Server
     *
     * @throws IOException
     */
    public static final String ANONYMOUS_USER = "anonymous";

    public void connect() throws Exception {
        if (client == null) {
            client = new FTPClient();
        }
        // 已经连接
        if (client.isConnected()) {
            return;
        }

        // 编码
        client.setControlEncoding(Control_Encoding);

        try {
            // 连接FTP Server
            client.connect(this.host, this.port);
            // 登陆
            if (this.user == null || "".equals(this.user)) {
                // 使用匿名登陆
                client.login(ANONYMOUS_USER, ANONYMOUS_USER);
            } else {
                client.login(this.user, this.password);
            }
            // 设置文件格式
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 获取FTP Server 应答
            int reply = client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                client.disconnect();
                throw new Exception("connection FTP fail!");
            }

            FTPClientConfig config = new FTPClientConfig(client.getSystemType().split(" ")[0]);
            config.setServerLanguageCode("zh");
            client.configure(config);
            // 使用被动模式设为默认
            client.enterLocalPassiveMode();
            // 二进制文件支持
            client.setFileType(FTP.BINARY_FILE_TYPE);
            // 设置模式
            client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);

        } catch (IOException e) {
            throw new Exception("connection FTP fail! " + e);
        }
    }

    /**
     * 断开FTP连接
     *
     * @throws IOException
     */
    public void close() {
        if (client != null && client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件列表
     *
     * @return
     */
    public List<FTPFile> list() {
        List<FTPFile> list = null;
        try {
            FTPFile ff[] = client.listFiles(ftpPath);
            if (ff != null && ff.length > 0) {
                list = new ArrayList<FTPFile>(ff.length);
                Collections.addAll(list, ff);
            } else {
                list = new ArrayList<FTPFile>(0);
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 切换目录
     *
     * @param path
     *            需要切换的目录
     * @param forcedIncrease
     *            如果目录不存在,是否增加
     */
    public void switchDirectory(String path, boolean forcedIncrease) {
        try {
            if (path != null && !"".equals(path)) {
                boolean ok = client.changeWorkingDirectory(path);
                if (ok) {
                    this.ftpPath = path;
                } else if (forcedIncrease) {
                    // ftpPath 不存在,手动创建目录
                    StringTokenizer token = new StringTokenizer(path, "\\//");
                    while (token.hasMoreTokens()) {
                        String npath = token.nextToken();
                        client.makeDirectory(npath);
                        client.changeWorkingDirectory(npath);
                        if (ok) {
                            this.ftpPath = path;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 创建目录
     *
     * @param path
     */
    public void createDirectory(String path) {
        try {
            if (path != null && !"".equals(path)) {
                boolean ok = client.changeWorkingDirectory(path);
                if (!ok) {
                    // ftpPath 不存在,手动创建目录
                    StringTokenizer token = new StringTokenizer(path, "\\//");
                    while (token.hasMoreTokens()) {
                        String npath = token.nextToken();
                        client.makeDirectory(npath);
                        client.changeWorkingDirectory(npath);
                    }
                }
            }
            client.changeWorkingDirectory(this.ftpPath);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 删除目录,如果目录中存在文件或者文件夹则删除失败
     *
     * @param path
     * @return
     */
    public boolean deleteDirectory(String path) {
        boolean flag = false;
        try {
            flag = client.removeDirectory(path);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除文件
     *
     * @param path
     * @return
     */
    public boolean deleteFile(String path) {
        boolean flag = false;
        try {
            flag = client.deleteFile(path);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 上传文件,上传文件只会传到当前所在目录
     *
     * @param localFile
     *            本地文件
     * @return
     */
    public boolean upload(File localFile) {
        return this.upload(localFile, "");
    }

    /**
     * 上传文件,会覆盖FTP上原有文件
     *
     * @param localFile
     *            本地文件
     * @param reName
     *            重名
     * @return
     */
    public boolean upload(File localFile, String reName) {
        boolean flag = false;
        String targetName = reName;
        // 设置上传后文件名
        if (reName == null || "".equals(reName)) {
            targetName = localFile.getName();
        }
        FileInputStream fis = null;
        try {
            // 开始上传文件
            fis = new FileInputStream(localFile);
            client.setControlEncoding(Control_Encoding);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            boolean ok = client.storeFile(targetName, fis);
            if (ok) {
                flag = true;
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 下载文件,如果存在会覆盖原文件
     *
     * @param ftpFileName
     *            文件名称,FTP上的文件名称
     * @param savePath
     *            保存目录,本地保存目录
     * @return
     */
    public boolean download(String ftpFileName, String savePath) {
        boolean flag = false;

        File dir = new File(savePath);

        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileOutputStream fos = null;
        try {
            String saveFile = dir.getAbsolutePath() + File.separator + ftpFileName;
            fos = new FileOutputStream(new File(saveFile));
            boolean ok = client.retrieveFile(ftpFileName, fos);
            if (ok) {
                flag = true;
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return flag;
    }

    public static void main(String args[]) {

        // 创建FTP对象
        FtpUtil ftp = new FtpUtil("10.204.20.157", 21, "etlpt", "ZHYQ@123");
        try {
            // 连接FTP
            ftp.connect();

            // 移动工作空间、切换目录
            System.out.println("当前位置:" + ftp.getHome());
            ftp.switchDirectory("/var/ftp/data/data/hive/exp/lab/area/", true);
            System.out.println("当前位置:" + ftp.getHome());

            // 查询目录下的所有文件夹以及文件
            List<FTPFile> list = ftp.list();
            System.out.println("|-- " + ftp.getHome());
            for (FTPFile f : list) {
                System.out.println(" |-- [" + (f.getType() == 0 ? "文件" : "文件夹") + "]" + f.getName());
            }

            // 上传文件
//            boolean r1 = ftp.upload(new File("C:\\Users\\joymt\\Documents\\ftp\\测试文件1.txt"), "测试文件2.txt");
//            System.out.println("上传文件:" + r1);

            // 下载文件
            boolean r2 = ftp.download("tb_dim_subarea_20211203.txt", "E:\\data");
            System.out.println("下载文件:" + r2);

//            // 删除文件
//            boolean r3 = ftp.deleteFile("/test/测试文件2.txt");
//            System.out.println("删除文件:" + r3);

//            // 删除目录
//            boolean r4 = ftp.deleteDirectory("/test");
//            System.out.println("删除目录:" + r4);

        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        ftp.close();
    }

}

3.FtpUtil工具类源码

FtpUtil工具类源码-Java文档类资源-CSDN下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值