廢話不多說,關鍵代碼如下所示::
包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根據配置遠程服務器地址下載文件到當前服務,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持! ,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!