美文网首页
使用comment-net工具实现FTP下载文件

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

作者: 葱大驴 | 来源:发表于2018-01-15 09:58 被阅读0次

为了实现一个从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() 才可以切换到根目录。

相关文章

网友评论

      本文标题:使用comment-net工具实现FTP下载文件

      本文链接:https://www.haomeiwen.com/subject/quvfoxtx.html