当前位置 博文首页 > ftpclient获取文件列表,ftpclient下载文件ftp目录下文件列表为

    ftpclient获取文件列表,ftpclient下载文件ftp目录下文件列表为

    作者:xiaoyingying 时间:2021-07-30 13:58

        关于使用FTPClient下载文件,获取文件列表为空的情况。以及报错Hostattemptingdataconnectionipaddressisnotsameasserver
        获取ftp目录下文件列表为空的情况
        FTPFile[]fs=ftp.listFiles(remotePath);
        这里代码获取fs的长度为0.很苦恼。
        奇怪的是我在我本机的windows系统下搭建的ftp服务器正常。但在linux下面却不行。
        只需要在加入下一行代码即可。
        //这个方法的意思就是每次数据连接之前,ftpclient告诉ftpserver开通一个端口来传输数据
        ftp.enterLocalPassiveMode();
       下载文件报Hostattemptingdataconnectionipaddressisnotsameasserver
        这个错误只有当我获取文件的地址为内网ip才会出现这种情况,需要修改一个设置。setRemoteVerificationEnabled
        服务器会获取自身Ip地址和提交的host进行匹配,当不一致时报出以上异常。
        将此参数设置为false即可。默认为true。
        ftp.setRemoteVerificationEnabled(false);
        ftp下载文件的代码如下:
        /**
        */**Description:从FTP服务器下载文件*
        *@paramurlFTP服务器hostname
        *@paramportFTP服务器端口
        *@paramusernameFTP登录账号
        *@parampasswordFTP登录密码
        *@paramremotePathFTP服务器上的相对路径
        *@paramfileName要下载的文件名
        *@paramlocalPath下载后保存到本地的路径
        *@return
        */
        publicbooleandownFile(StringremotePath,StringfileName,
        StringlocalPath){
        booleansuccess=false;
        try{
        if(!ftp.isConnected()){
        logger.debug("获取文件失败");
        returnfalse;
        }
        //这个方法的意思就是每次数据连接之前,ftpclient告诉ftpserver开通一个端口来传输数据。
        //为什么要这样做呢,因为ftpserver可能每次开启不同的端口来传输数据,但是在linux上或者其他服务器上面,
        //由于安全限制,可能某些端口没有开启,所以就出现阻塞。
        ftp.enterLocalPassiveMode();
        ftp.setRemoteVerificationEnabled(false);
        ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
        FTPFile[]fs=ftp.listFiles(remotePath);
        booleanfileExsit=false;
        for(FTPFileff:fs){
        if(ff.getName().equals(fileName)){
        fileExsit=true;
        FilelocalFile=newFile(localPath+"/"+ff.getName());
        OutputStreamis=newFileOutputStream(localFile);
        ftp.retrieveFile(ff.getName(),is);
        is.close();
        break;
        }
        }
        if(!fileExsit){
        System.out.println("文件不存在");
        returnsuccess;
        }
        success=true;
        }catch(IOExceptione){
        e.printStackTrace();
        thrownewServiceException("下载文件失败");
        }
        returnsuccess;
        }
        原文:https://www.cnblogs.com/hisunhyx/p/5029476.html