使用comment-net工具实现FTP下载文件

为了实现一个从FTP地址批量下载文件的功能,使用了comment-net.jar包。

主要实现代码

  1. 获得FTP链接,返回FTPClient类的方法
/**
     * 获得FTP客户端
     * @param hostName 主机名称
     * @param username 用户账号
     * @param password 密码
     * @return FTPClient引用
     */
    public  static FTPClient getFTPClient(String hostName, String username , String password,int port){
        FTPClient ftpClient = new FTPClient();
        port = port == 0 ?21:port; //port默认值21
        try {
            ftpClient.connect(hostName,port);
            ftpClient.login(username, password);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.err.println("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//二进制文件类型
                ftpClient.enterLocalPassiveMode();
                System.out.println("FTP连接成功。");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("ip地址可能出错");
        }
        return ftpClient;
    }
  1. 下载文件的方法
 public static void downloadFtpFile(FTPClient ftpClient,String ftpFilePath,String localPath,String ftpFileName,String localNewFileName){
        try {

            ftpClient.changeWorkingDirectory(ftpFilePath.trim());//选择路径
            OutputStream os = new FileOutputStream((localPath+File.separator+localNewFileName).trim());
            System.out.println("正在访问FTP路径:"+ftpClient.printWorkingDirectory()+"下载文件["+ftpFileName+"] 到["+localPath+"]");//打印当前路径
            ftpClient.retrieveFile(ftpFileName,os);
            ftpClient.changeToParentDirectory();
            ftpClient.changeToParentDirectory();
            os.close();


        } catch (IOException e) {
            System.err.println("保存文件出错");
            e.printStackTrace();
        }

    }

需要注意的是

  • ftp的路径使用的路径分隔是 /
  • 在下载文件过程中要切换路径,我一开始直接调用了boolean changeWorkingDirectory(String pathname)方法,无效。
    查看文档,选择了changeToParentDirectory() 方法,无效。看了网上其他人的说明之后,调用2次changeToParentDirectory() 才可以切换到根目录。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,679评论 25 708
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,196评论 6 13
  • 我想我是一个经不住诱惑的人所以才会有了今天的我,20岁了半死不说的躺在校园里,嘴里喊着拒绝浪费生命。所以这几年来我...
    野渡无人舟自横mable阅读 359评论 0 2
  • 代理模式 官方解释Delegation is a simple and powerful pattern in w...
    家丁三锅阅读 395评论 0 0