Java使用FTPClient 上传文件、下载文件、删除文件

 在连接ftp服务器时,刚开始密码弄错了,使用工具FlashFXP修改密码后就能连上,

FileZilla连接时,报证书过期,选择信任该证书并继续登录,登录不上,修改密码后报同样的错误,后来在编辑中选择清除个人信息,全部选中(包括快速连接栏历史,重新连接信息,站点管理器条目和传输队列)后删除,重新添加新站点后可以连接。

package com.sany.newmes.util;


import org.apache.commons.net.ftp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.SocketException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created on 2021/3/15.
 *
 * @author
 */
public class FtpTest {
    private static final Logger logger = LoggerFactory.getLogger(FtpTest.class);
    /**
     * 本地字符编码
     */
    private static String LOCAL_CHARSET = "UTF-8";

    // FTP协议里面,规定文件名编码为iso-8859-1
    private static String SERVER_CHARSET = "ISO-8859-1";
    //ftp的端口,主机,用户名和密码
    private static int port = 60021;
    private static String host = "10.0.66.246";
    private static String username = "scr";
    private static String password = "0ljmnrw0i?D";

    /**
     * 获取FTPClient对象
     *
     * @param ftpHost     FTP主机服务器
     * @param ftpPassword FTP 登录密码
     * @param ftpUserName FTP登录用户名
     * @param ftpPort     FTP端口 默认为21
     * @return
     */
    public static FTPSClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
        FTPSClient ftpClient = null;
        try {
            //创建SSL上下文
            SSLContext sslContext = SSLContext.getInstance("TLS");
            //自定义证书,忽略已过期证书
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
                @Override
                public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}
            };
            //初始化
            sslContext.init(null, new X509TrustManager[] { trustManager }, null);
            ftpClient = new FTPSClient(sslContext);

//            ftpClient.setConnectTimeout(1000000);
//            ftpClient.enterLocalPassiveMode();
//            ftpClient.setControlEncoding("UTF-8");
//            FTPClientConfig config = new FTPClientConfig();
//            config.setLenientFutureDates(true);

            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            Boolean login = ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            logger.info("login: "+login);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.info("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                logger.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.info("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("FTP的端口错误,请正确配置。");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }

    /**
     * Description: 向FTP服务器上传文件
     *
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input    输入流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String basePath, String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPSClient ftpClient = null;
        try {
            int reply;
            ftpClient = getFTPClient(host, port, username, password);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return result;
            }
            // 切换到上传目录
            if (!ftpClient.changeWorkingDirectory(basePath + filePath)) {
                // 如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) {
                        continue;
                    }
                    tempPath += "/" + dir;
                    if (!ftpClient.changeWorkingDirectory(tempPath)) {
                        if (!ftpClient.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftpClient.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            // 设置上传文件的类型为二进制类型
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.execPROT("P");
            ftpClient.execPBSZ(0);
            ftpClient.setControlEncoding(LOCAL_CHARSET);
            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
            // 上传文件
            filename = new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
            if (!ftpClient.storeFile(filename, input)) {
                return result;
            }

            if (null != input) {
                input.close();
            }

            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    //退出登录
                    ftpClient.logout();
                    //关闭连接
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
    /**
     * 从FTP服务器下载文件
     *
     * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
     *
     * @param localPath 下载到本地的位置 格式:H:/download
     *
     * @param fileName 文件名称
     */
    public static void downloadFtpFile(String ftpPath, String localPath, String fileName) {

        FTPSClient ftpSClient = null;
        try {
            ftpSClient = getFTPClient(host, port, username, password);

            if (FTPReply.isPositiveCompletion(ftpSClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                LOCAL_CHARSET = "UTF-8";
            }
            ftpSClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpSClient.execPROT("P");
            ftpSClient.setControlEncoding(LOCAL_CHARSET);
            ftpSClient.enterLocalPassiveMode();// 设置被动模式
            ftpSClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
            Boolean s = ftpSClient.changeWorkingDirectory(ftpPath);
//            方法一
             File localFile = new File(localPath + File.separatorChar + fileName);
             OutputStream os = new FileOutputStream(localFile);
             ftpSClient.retrieveFile(new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET), os);
            os.close();
        } catch (FileNotFoundException e) {
            logger.error("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            logger.error("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("文件读取错误。");
            e.printStackTrace();
        } finally {

            if (ftpSClient.isConnected()) {
                try {
                    //退出登录
                    ftpSClient.logout();
                    //关闭连接
                    ftpSClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
    /**
     * 删除文件
     *
     * @param pathname
     *            FTP服务器保存目录
     * @param filename
     *            要删除的文件名称
     * @return
     */
    public static boolean deleteFile(String pathname,String filename) {
        boolean flag = false;
        FTPSClient ftpSClient = new FTPSClient();
        try {
            ftpSClient = getFTPClient(host, port, username, password);
            // 验证FTP服务器是否登录成功
            int replyCode = ftpSClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                return flag;
            }
            // 切换FTP目录
            ftpSClient.changeWorkingDirectory(pathname);
            // 设置上传文件的类型为二进制类型
            if (FTPReply.isPositiveCompletion(ftpSClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                LOCAL_CHARSET = "UTF-8";
            }
            ftpSClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpSClient.execPROT("P");
            ftpSClient.setControlEncoding(LOCAL_CHARSET);
            ftpSClient.enterLocalPassiveMode();// 设置被动模式
            ftpSClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
            //对中文名称进行转码
            filename = new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
            ftpSClient.dele(filename);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftpSClient.isConnected()) {
                try {
                    //退出登录
                    ftpSClient.logout();
                    //关闭连接
                    ftpSClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
        return flag;
    }
    public static void main(String[] args) throws FileNotFoundException {

        //ftp服务器路径
        String ftpPath = "/home/scr/";
        //本地路径
        String localPath = "F://";
        //文件名
//        String fileName = "Koala.jpg";
//        String fileName = "新建 Microsoft Excel 工作表.xlsx";
        String fileName = "接口测试.docx";

        //下载
        //将ftp根目录下的文件下载至E盘
        FtpTest.downloadFtpFile(ftpPath, localPath, fileName);

        //上传
        //将E盘的文件上传至ftp根目录
//        FileInputStream in=new FileInputStream(new File(localPath + fileName));
//        FtpTest.uploadFile("/home/scr", "/", fileName, in);

        //删除ftp根目录下的文件
//        FtpTest.deleteFile(ftpPath, fileName);

    }
}

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值