Java实现FTP服务器文件的上传和下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37591536/article/details/83061382

一、前言:

最近刚好需要实现这个功能:实现ftp的上传和下载。在网上找了下资料,总结了下。直接上代码:

二、代码示例:

首先使用到的maven依赖:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>1.4.1</version>
</dependency>

ftp工具类:

package com.left.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;

/**
 * <pre>
 *     @author : orange
 *     e-mail : [email protected]
 *     time   : 2018/10/09 14:18
 *     desc   : ftp下载工具
 *     version: 1.0
 * </pre>
 */
@Slf4j
public class FtpUtil {

    /**
     * 获取FTPClient对象
     *
     * @param ftpHost     FTP主机服务器
     * @param ftpPassword FTP 登录密码
     * @param ftpUserName FTP登录用户名
     * @param ftpPort     FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.out.println("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                System.out.println("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            System.out.println("FTP的IP地址可能错误,请正确配置。");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }

    /*
     * 从FTP服务器下载文件
     *
     * @param ftpHost FTP IP地址
     * @param ftpUserName FTP 用户名
     * @param ftpPassword FTP用户名密码
     * @param ftpPort FTP端口
     * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
     * @param localPath 下载到本地的位置 格式:H:/download
     * @param fileName 文件名称
     */
    public static boolean downloadFtpFile(String ftpHost, String ftpUserName,
                                          String ftpPassword, int ftpPort, String ftpPath, String localPath,
                                          String fileName) {

        FTPClient ftpClient = null;

        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);
            File localFile = new File(localPath + File.separatorChar + fileName);
            OutputStream os = new FileOutputStream(localFile);
            ftpClient.retrieveFile(fileName, os);
            os.close();
            ftpClient.logout();
        } catch (FileNotFoundException e) {
            log.info("没有找到" + ftpPath + "文件");
            e.printStackTrace();
            return false;
        } catch (SocketException e) {
            log.info("连接FTP失败.");
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            log.info("文件读取错误。");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * Description: 向FTP服务器上传文件
     *
     * @param ftpHost     FTP服务器hostname
     * @param ftpUserName 账号
     * @param ftpPassword 密码
     * @param ftpPort     端口
     * @param ftpPath     FTP服务器中文件所在路径 格式: ftptest/aa
     * @param fileName    ftp文件名称
     * @param input       文件流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String ftpHost, String ftpUserName,
                                     String ftpPassword, int ftpPort, String ftpPath,
                                     String fileName, InputStream input) {
        boolean success = false;
        FTPClient ftpClient = null;
        try {
            int reply;
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return success;
            }
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);

            ftpClient.storeFile(fileName, input);

            input.close();
            ftpClient.logout();
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

    /**
     * 方法描述:检验指定路径的文件是否存在ftp服务器中
     *
     * @param filePath 指定绝对路径的文件/TEST/20161010
     * @return 存在返回true,不存在返回false
     */
    public static boolean isFTPFileExist(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort, String fileName, String filePath) {

        FTPClient ftpClient = null;
        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            ftpClient.setControlEncoding("GBK"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            // 进入文件所在目录,注意编码格式,以能够正确识别中文目录
            ftpClient.changeWorkingDirectory(new String(filePath.getBytes("GBK"),
                    FTP.DEFAULT_CONTROL_ENCODING));
            // 检验文件是否存在
            InputStream is = ftpClient.retrieveFileStream(new String(fileName
                    .getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
            if (is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
                log.info("文件" + filePath + "/" + fileName + "不存在");
                return false;
            }
            log.info("文件" + filePath + "/" + fileName + "存在");
            if (is != null) {
                is.close();
                ftpClient.completePendingCommand();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ftpClient != null) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }


    public static void main(String[] args) {

        String ftpHost = "60.12.107.83";
        String ftpUserName = "sl0571";
        String ftpPassword = "sl123456";
        int ftpPort = 10021;
        String ftpPath = "/data/yzf_ftp/kwy_ftp";
        String localPath = "E:\\card";
        String fileName = "20181014.txt";
//        FTPClient ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
        boolean ftpFileExist = isFTPFileExist(ftpHost, ftpUserName, ftpPassword, ftpPort, fileName, ftpPath);
        if(ftpFileExist) {
        boolean downloadFtpFile = downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
        System.out.println("下载结果:" + downloadFtpFile);
        }
//        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_37591536/article/details/83061382