FTP工具类

该博客提供了一个Java实现的FTPUtil工具类,用于从FTP服务器下载文件和目录,以及上传文件到FTP服务器。类中包含了downloadFileFromFtp、downOneFileFromFtp和uploadFtpFile等方法,支持被动模式连接,处理FTP文件操作异常,并使用Apache Commons Net库进行FTP通信。
摘要由CSDN通过智能技术生成
package com.xx.epolicy.util;

import com.xx.epolicy.Exception.FtpException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/*<dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.3</version>
        </dependency>
*/

import java.io.*;


public class FTPUtil {
    /**
     * 从FTP上下载文件
     * @param url
     * @param username
     * @param password
     * @param remotePath
     * @param localPath
     * @return
     */
    public static void downFileFromFtp(
            String url, //FTP服务器hostname
            int port, //port端口
            String username, //FTP登录账号
            String password, //FTP登录密码
            String remotePath,//FTP服务器上的相对路径
            String localPath//下载后保存到本地的路径
    ) throws Exception {
        File file = new File(localPath);
        if(!file.isDirectory()){
            file.mkdirs();
        }
        FTPClient ftp = getFTPClient(url, port, username, password);
        try {
            writeFtpFile(ftp,remotePath,localPath);
            ftp.logout();
        } finally {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        }
    }

    /**
     * 从FTP上下载指定文件
     * @param url
     * @param port
     * @param username
     * @param password
     * @param remotePath
     * @param remoteFileName
     * @param localFilePath
     * @throws Exception
     */
    public static void downOneFileFromFtp(
            String url, //FTP服务器hostname
            int port, //port端口
            String username, //FTP登录账号
            String password, //FTP登录密码
            String remotePath,//FTP服务器上的相对路径
            String remoteFileName,//需下载的文件名
            String localFilePath//下载后保存到本地的路径
    ) throws Exception {
        FTPClient ftp = getFTPClient(url, port, username, password);
        OutputStream os = null;
        try {
            boolean b = ftp.changeWorkingDirectory(remotePath);
            if(!b){
                throw new FtpException("ftp连接地址不存在,请检查");
            }
           if(!new File(localFilePath).isDirectory()) {
               new File(localFilePath).mkdirs();
           }
            File localFile = new File(localFilePath+"/"+remoteFileName);

            os = new FileOutputStream(localFile);
            boolean result = ftp.retrieveFile(remoteFileName, os);
            if(!result){
                throw new FtpException("FTP文件下载失败");
            }
        } finally {
            os.close();
            ftp.logout();
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        }
    }

    public static boolean uploadFtpFile(String url,int port,String username, String password, String path, String filename, InputStream input)throws Exception {
        FTPClient ftp = getFTPClient(url, port, username, password);
        try {
            boolean b = ftp.changeWorkingDirectory(path);
            if(!b){
                throw new Exception("ftp连接地址不存在,请检查");
            }
            return ftp.storeFile(filename, input);
        }  finally {
            input.close();
            ftp.logout();
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        }
    }



    public static boolean uploadCMBFtpFile(String url,int port,String username, String password, String path, String filename, InputStream input)throws Exception {
        FTPClient ftp = getFTPClient(url, port, username, password);
        try {
            boolean b = ftp.changeWorkingDirectory(path);
            if(!b){
                boolean makeDirectory = ftp.makeDirectory(path);
                b = ftp.changeWorkingDirectory(path);
                if(!b){
                    throw new Exception("ftp连接地址不存在,请检查");
                }
            }
            return ftp.storeFile(filename, input);
        }  finally {
            input.close();
            ftp.logout();
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        }
    }




    /**
     * 递归方法,当读取的FTP路径下含有子目录时,将子目录的文件也一并读取
     * @param ftp
     * @param remotePath
     * @param localPath
     * @throws Exception
     */
    private static void writeFtpFile(FTPClient ftp,String remotePath,String localPath) throws Exception {
        boolean b = ftp.changeWorkingDirectory(remotePath);
        if(!b){
            throw new Exception("ftp连接地址不存在,请检查");
        }
        FTPFile[] fs = ftp.listFiles();
        if(fs.length>0){
            for(FTPFile ff:fs){
                if(ff.isDirectory()){
                    writeFtpFile(ftp,ff.getName(),localPath);
                }else {
                    File localFile = new File(localPath + "/" + ff.getName());
                    OutputStream os = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), os);
                    os.close();
                }
            }
        }
        ftp.changeWorkingDirectory("../");
    }

    private static FTPClient getFTPClient(String url, int port, String username, String password) throws Exception {
        FTPClient ftp = new FTPClient();
        int reply;
        ftp.connect(url,port);
        //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new Exception("FTP服务器连接异常");
        }
        ftp.setControlEncoding("UTF-8");
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //提前开启端口,防止linux阻塞
        ftp.enterLocalPassiveMode();
        return  ftp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值