废话不多说,关键代码如下所示::
包com.eastrobot.remote;导入java.util.list;导入java.util.concurrent.executorservice;导入java.util.concurrent.executors;导入org.apache.commons.logging.log;导入org.apache.commons.logging.logfactory;导入com.eastrobot.util.propertiesutil; /** * full.zhang * * ftp/sftp抽象方法类 * */公共抽象类FileRemote {私有静态最终字符串ftp_mode =“ ftp”;私有静态最终字符串sftp_mode =“ sftp”;公共静态字符串ftproot;公共静态字符串模式;公共静态字符串主机;公共静态字符串用户名;公共静态字符串密码;公共静态字符串端口;私有静态filemote客户端= null; //最大一次性下载50个文件public static int max = 50;私有最终静态日志记录器= logFactory.getLog(fileremote.class); public static fileRemote getInstance(){if(client == null){ftproot = propertiesutil.getString(“ trassing.root”); mode = propertiesutil.getString(“ trass.mode”); host = propertiesUtil.getString(“ Transfer.host”);用户名= propertiesutil.getString(“ trass.username”); password = propertiesUtil.getString(“ Transfer.Password”); port = propertiesutil.getString(“ transfer.port”); if(mode.equals(ftp_mode)){client = new fileftPremote(); } else if(mode.equals(sftp_mode)){client = new fileftpremote(); }}返回客户端; } / ** *执行定时任务 * / public void process(){logger.debug(“ -----------------------------------------------------------------------”); //创建线程池executorService exec = executors.newsinglethreadexecutor(); exec.execute(new runnable(){@Override public void Run(){//建立连接initsftpinfo(主机,端口,端口,用户名,密码); // list <String> listsourceSourcePath = listremoteFilePath(ftpRoot); ftproot); if(listsourcepath.isement.isempty emptiment) closeconnection() exec.shutdown(); } / ** *初始化连接 * * * @param主机 * @param port * @param用户名 * @param password * @throws exception * @return * / public Abstract void Initftpinfo(字符串主机,字符串port,字符串端口,字符串用户名,字符串密码); / ** * * * * * @param路径 * @return * @throws except */ public Abstract void downloadremotefile(字符串filepath); / ** *获取远程服务下指定目录下的所有文件路径集合(包含子目录下文件) * * @param路径 * @return */ public Abstract List <string> listremoteFilePath(String path); / ** *释放连接 */公共摘要void colleconnection(); } [java]查看纯copypackage com.eastrobot.remote;导入java.io.file;导入java.io.io.fileoutputstream;导入java.io.ioexception;导入java.io.outputstream;导入java.util.arraylist;导入java.util.list;导入org.apache.commons.io.ioutils;导入org.apache.commons.lang.stringutils;导入org.apache.commons.logging.log;导入org.apache.commons.logging.logfactory;导入org.apache.commons.net.ftp.ftpclient;导入org.apache.commons.net.ftp.ftpfile;导入org.apache.commons.net.ftp.ftpreply;导入com.eastrobot.command.commander;公共类FileftPremote扩展了FileRemote {受保护的FTPCLIENT FTPCLIENT;私有字符串编码=“ UTF-8”;私人布尔二进制二进制= true;私有最终静态日志记录器= logfactory.getLog(fileftPremote.class); @Override public void Initftpinfo(字符串主机,字符串端口,字符串用户名,字符串密码){尝试{//构造一个ftpclient实例ftpclient = ftpclient = new ftpclient(); //设置字符集ftpclient.setControlenCoding(编码); //连接ftp ftpclient.connect(host,stringutils.isnotblank(port)?integer.valueof(port):21); //连接后检测返回码来校验连接是否成功int回复= ftpclient.getReplyCode(); if(ftpreply.ispositivecompletion(reply)){//登陆到ftp服务器if(ftpClient.login(username,password)){setFileType(); } ftpclient.login(用户名,密码); } else {ftpClient.disconnect(); logger.error(“ ftp服务拒绝连接!”); }} catch(异常E){if(ftpClient.isconnected()){try {ftpclient.disconnect(); //断开连接} catch(ioexception e1){logger.error(“ ftp服务连接断开失败!”); }} logger.error(“ ftp服务连接失败!”); }} / ** *设置文件传输类型 * / private void setFileType(){尝试{if(binaryTransfer){ftpclient.setfiletype(ftpclient.binary_file_type); } else {ftpclient.setFiletype(ftpclient.ascii_file_type); }} catch(ioexception e){e.printstacktrace(); }} @Override public void downloadRemoteFile(string filepath){if(stringutils.endswith(filepath,“/”)|| strignutils.endswith(filepath,file.separator)){filepath = filepath = filepath = filepath.substring(0,filepath.lifepath.length.length.lengthralgth(filepath.lengthresptring) - 长度() - 1); }文件savefile = new文件(filepath); if(savefile.exists()){return; } //文件所在目录字符串路径= filepath.substring(0,filepath.lastindexof(“/”)); if(!strignutils.endswith(path,“/”)&&!stringutils.endswith(path,file.separator)){if(commander.islinux){path = path = path + path + file.separator; } else {路径=路径 +“/”; }} outputStream输出= null;尝试{//创建目标文件路径if(!savefile.getParentFile()。 } savefile.createnewfile(); //转移到ftp ftpClient.ChangeWorkingDirectory(path); output = new fileOutputstream(savefile); ftpclient.retrievfile(filepath,output); } catch(ioexception e){logger.debug(“文件:” + filepath +“ _________________________________!”); e.printstacktrace(); }最后{logger.debug(“文件:” + filepath +“ ________________________________!”); ioutils.closequietly(输出); }} @Override public List <string> listremoteFilePath(String path){list <String> list = new ArrayList <string>();尝试{if(!strimutils.endswith(path,“/”)&&!stringutils.endswith(path,file.separator)){if(commander.islinux){path = path = path = path + file.separator; } else {路径=路径 +“/”; }} boolean changeir = ftpclient.changeworkingDirectory(path); if(changeir){ftpClient.setControlenCoding(编码); ftpfile [] files = ftpclient.listfiles(); for(ftpfile文件:files){if(list.size()> = max){break; } if(file.isdirectory()){if(!strimutils.endswith(path,“/”)&&!strimutils.endswith(path,file.separator)){if(commander.islinux){path = path = path = path = path = file + file + file.separator; } else {路径=路径 +“/”; }} list.addall(this.listremoteFilePath(path + file.getName())); } else if(changeir){if(!strignutils.endswith(path,“/”)&&!strimutils.endswith(path,path,file.separator)){if(commander.islinux){path = path = path + file.separator; } else {路径=路径 +“/”; }} file savefile = new file(path + file.getName()); if(!savefile.exists()){list.add(path + file.getName()); }}}}}} catch(异常e){e.printstacktrace(); }返回列表; } @Override public void colleconnection(){if(ftpClient!= null){try {ftpclient.logout(); } catch(ioexception e){e.printstacktrace(); }最后{if(ftpClient.isconnected()){try {ftpclient.disconnect(); } catch(ioexception e){e.printstacktrace(); }}}}}}} [Java]查看plain copypackage com.eastrobot.remote;导入java.io.file;导入java.io.io.fileoutputstream;导入java.util.arraylist;导入java.util.list;导入java.util.properties;导入Java.util.Vector;导入org.apache.commons.io.ioutils;导入org.apache.commons.lang.stringutils;导入org.apache.commons.logging.log;导入org.apache.commons.logging.logfactory;导入com.eastrobot.command.commander;导入com.jcraft.jsch.channel;导入com.jcraft.jsch.channelsftp;导入com.jcraft.jsch.jsch;导入com.jcraft.jsch.session;导入com.jcraft.jsch.sftpattrs;导入com.jcraft.jsch.sftpexception;导入com.jcraft.jsch.channelsftp.lsentry; Public Class FilestPremote扩展了FileRemote {受保护的会话= null;受保护的ChannelsFTP通道= null;私有最终静态日志记录器= logfactory.getLog(fileftpremote.class); @Override public void Initftpinfo(字符串主机,字符串端口,字符串用户名,字符串密码){try {jsch jsch = new jsch(); //创建jsch对象会话= jsch.getSession(用户名,host,stringutils.isnotblank(port)?integer.value.valueof(port):22); Session.SetPassword(密码); //设置密码properties config = new properties(); config.put(“ stricthostkeychecking”,“ no”); session.setConfig(config); //为会话对象设置properties session.setTimeout(60000); // timeouts session.connect(); //通过会话建立链接频道chan = session.openchannel(“ sftp”); //打开sftp通道chan.connect(); //建立sftp通道的连接通道=(channelsftp)chan; } catch(异常e){logger.error(“ sftp连接失败”); e.printstacktrace(); }} @Override public void downloadRemoteFile(string filepath){if(stringutils.endswith(filepath,“/”)|| strignutils.endswith(filepath,file.separator)){filepath = filepath = filepath = filepath.substring(0,filepath.lifepath.length.length.lengthralgth(filepath.lengthresptring) - 长度() - 1); }文件savefile = new文件(filepath); fileOutputStream输出= null;尝试{if(savefile.exists()){return; } // if(!savefile.getParentFile()。 } savefile.createnewfile(); //文件所在目录字符串路径= filepath.substring(0,filepath.lastindexof(“/”)); if(!strignutils.endswith(path,“/”)&&!stringutils.endswith(path,file.separator)){if(commander.islinux){path = path = path + path + file.separator; } else {路径=路径 +“/”; }} channel.cd(path); channel.get(filepath,new fileOutputStream(savefile)); logger.debug(“文件:” + filepath +“ _____________________________________________________________________________________________________________”); } catch (Exception e) { LOGGER.debug("文件:" + filePath + "____________________________________________下载失败!"); e.printstacktrace(); }最后{ioutils.closequietly(输出); }} @suppresswarnings(“ un oftched”)@Override public list <string> listremoteFilePath(string path){list <string> list = new arraylist <new arraylist <string>(); vector <lsentry> v = null;尝试{if(!strimutils.endswith(路径,“/”)&& stringutils.endswith(path,file.separator)){path = path = path = path + file.separator; } v = channel.ls(path); } catch(sftpexception e){e.printstacktrace(); } for(lsentry lsentry:v){if(list.size()> = max){break; } if(!“。”。等equals(lsentry.getFilename())&&!! if(attr.isdir()){if(!stringutils.endswith(path,“/”)&&!stringutils.endswith(path,path,file.separator))){if(commander.islinux){path = path = path + file + file.separator; } else {路径=路径 +“/”; }} list.addall(this.listremotefilepath(path + lsentry.getFileName())); } else {if(!strignutils.endswith(path,“/”)&&!strimutils.endswith(path,file.separator)){if(commander.islinux){path = path = path + path + file.separator; separator; } else {路径=路径 +“/”; }} file savefile = new file(path + lsentry.getFilename());如果(!savefile.exists()){list.add(path + lsentry.getFilename()); }}}}返回列表; } @Override public void colleconnection(){try {if(channel!= null){channel.quit(); channel.disconnect(); } if(session!= null){session.disconnect(); }} catch(异常e){e.printstacktrace(); }} public session getsession(){返回会话; } public void setSession(session){this.session = session; } public ChannelsFTP getChannel(){返回频道; } public void setChannel(ChannelsFTP Channel){this.Channel = Channel; }}}以上所述是小编给大家介绍的sftp和ftp根据配置远程服务器地址下载文件到当前服务,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!