废话不多说 , : :
package com.eastrobot.remote; Importer java.util.list; Importer java.util.concurrent.executorService; Importer java.util.concurrent.executors; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; import com.eastrobot.util.propertiesutil; / ** * full.zhang * * ftp / sftp 抽象方法类 * * / public abstrait class fileMote {private static final String ftp_mode = "ftp"; chaîne finale statique privée sftp_mode = "sftp"; String statique public ftproot; Mode de chaîne statique publique; hôte de chaîne statique publique; Nom d'utilisateur de chaîne statique publique; Mot de passe de chaîne statique publique; Port de chaîne statique publique; Client FileMote statique privé = null; // 最大一次性下载 50 个文件 public static int max = 50; Logger du journal statique final privé = logfactory.getLog (fileMote.class); public static fileMote getInstance () {if (client == null) {ftproot = propertiesUtil.getString ("transfer.root"); mode = propertiesUtil.getString ("transfer.mode"); host = propertiesUtil.getString ("transfer.host"); username = propertiesUtil.getString ("transfer.username"); mot de passe = 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 (); }} return client; } / ** * 执行定时任务 * / public void process () {logger.debug ("---------------------------------------- 进入定时下载远程文件"); // 创建线程池 ExecutorService exec = exécutor exec.execute (new Runnable () {@Override public void run () {// 建立连接 initftpinfo (hôte, port, nom d'utilisateur, mot de passe); // 远程服务所有源文件路径集合 list <string> listSourcePath = listremoteFilepath (ftproot); if (listSourcePath.isempty ()) {logger.debug ("____________."); Client.CloseConnection (); }); exec.shutdown (); } / ** * 初始化连接 * * @param hôte * @param port * @param nom d'utilisateur * @param mot de passe * @throws exception * @return * / public abstract void initftpinfo (hôte de chaîne, port de chaîne, nom d'utilisateur de chaîne, mot de passe de chaîne); / ** * 下载远程服务下文件到本地服务 * * @param path * @return * @throws exception * / public abstract void downloadRemotefile (String FilePath); / ** * 获取远程服务下指定目录下的所有文件路径集合 (包含子目录下文件) * * @param path * @return * / public abstract list <string> listremotefilepath (String Path); / ** * 释放连接 * / Public Résumé void CloseConnection (); } [Java] Voir le Copypackage ordinaire com.Eastrobot.Remote; Importer java.io.file; Importer java.io.fileOutputStream; Importer java.io.ioException; import java.io.outputStream; import java.util.arraylist; Importer java.util.list; import org.apache.commons.io.ioutils; import org.apache.commons.lang.stringutils; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; import org.apache.commons.net.ftp.ftpclient; import org.apache.commons.net.ftp.ftpfile; import org.apache.commons.net.ftp.ftpreply; import com.eastrobot.command.comder; La classe publique FileFtPremote étend FileMote {protégé ftpClient ftpClient; Encoding de chaînes privées = "UTF-8"; BinaryTransfer binaire privé = true; Logger de journal statique final privé = logfactory.getLog (fileftpremote.class); @Override public void initftpinfo (string host, String Port, String username, String Motword) {try {// 构造一个 ftpClient 实例 ftpClient = new ftpClient (); // 设置字符集 ftpclient.setControlenceding (codage); // 连接 ftp 服务器 ftpclient.connect (hôte, stringUtils.isnotblank (port)? Integer.Valueof (port): 21); // 连接后检测返回码来校验连接是否成功 int réponse = ftpclient.getReplyCode (); if (ftpreply.ispositivecompletion (réponse)) {// 登陆到 ftp 服务器 if (ftpclient.login (nom d'utilisateur, mot de passe)) {setFileType (); } ftpclient.login (nom d'utilisateur, mot de passe); } else {ftpClient.disconnect (); Logger.Error ("FTP 服务拒绝连接!"); }} catch (exception e) {if (ftpclient.isconnected ()) {try {ftpClient.disconnect (); // 断开连接} catch (ioException e1) {logger.error ("ftp 服务连接断开失败!"); }} Logger.error ("ftp 服务连接失败!"); }} / ** * 设置文件传输类型 * / private void setFileType () {try {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, "/") || stringUtils.endswith (filepath, file.separator)) {filepath = filepath.substring (0, filepath.length () - 1); } Fichier SaveFile = nouveau fichier (filepath); if (SaveFile.exists ()) {return; } // 文件所在目录 String Path = filePath.SubString (0, filepath.LastIndexof ("/")); if (! StringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commandant.islinux) {path = path + file.separator; } else {path = path + "/"; }} OutputStream output = null; essayez {// 创建目标文件路径 if (! SaveFile.GetParentFile (). existant ()) {SaveFile.GetParentFile (). MKDIRS (); } SaveFile.CreateEwFile (); // 转移到 ftp 服务器目录 ftpclient.changeworkingDirectory (chemin); Output = new FileOutputStream (SaveFile); ftpClient.RetReeveFile (filepath, sortie); } catch (ioException e) {logger.debug ("文件:" + filepath + "______________________ 下载失败!"); e.printStackTrace (); } Enfin {logger.debug ("文件:" + filepath + "______________________ 下载成功!"); Ioutils.closequietly (sortie); }} @Override public list <string> listreMoteFilePath (String path) {list <string> list = new ArrayList <string> (); essayez {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commandant.islinux) {path = path + file.separator; } else {path = path + "/"; }} booléen changér = ftpclient.changeworkingDirectory (path); if (changolIr) {ftpClient.setControleCcoding (Encoding); Ftpfile [] files = ftpclient.listFiles (); pour (ftpfile file: fichiers) {if (list.size ()> = max) {break; } if (file.isdirectory ()) {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commandant.islinux) {path = path + file.separator; } else {path = path + "/"; }} list.addall (this.ListremoteFilePath (path + file.getName ())); } else if (changéir) {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commandant.islinux) {path = path + file.separator; } else {path = path + "/"; }} File SaveFile = new File (path + file.getName ()); if (! SaveFile.exists ()) {list.add (path + file.getName ()); }}}}} catch (exception e) {e.printStackTrace (); } Retour List; } @Override public void CloseConnection () {if (ftpClient! = Null) {try {ftpClient.logout (); } catch (ioException e) {e.printStackTrace (); } enfin {if (ftpclient.isconnected ()) {try {ftpClient.disconnect (); } catch (ioException e) {e.printStackTrace (); }}}}}} [java] Voir le Copypackage ordinaire com.Eastrobot.remote; Importer java.io.file; Importer java.io.fileOutputStream; import java.util.arraylist; Importer java.util.list; import java.util.properties; Importer java.util.vector; import org.apache.commons.io.ioutils; import org.apache.commons.lang.stringutils; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; import com.eastrobot.command.comder; import com.jcraft.jsch.channel; import com.jcraft.jsch.channelsftp; import com.jcraft.jsch.jsch; import com.jcraft.jsch.Session; import com.jcraft.jsch.sftpattrs; import com.jcraft.jsch.sftPException; import com.jcraft.jsch.channelsftp.lsentry; classe publique FilesftPremote étend FileMote {Session Protected Session Session = NULL; canal protégés canalsftp = null; Logger de journal statique final privé = logfactory.getLog (fileftPremote.class); @Override public void initftpinfo (string host, String Port, String username, String Motword) {try {jsch jsch = new jsch (); // 创建 jsch 对象 session = jsch.getSession (nom d'utilisateur, hôte, stringUtils.isnotblank (port)? Integer.valueof (port): 22); session.setpassword (mot de passe); // 设置密码 Properties config = new Properties (); config.put ("stricthostKeyCheckking", "non"); session.setConfig (config); // 为 Session 对象设置 Propriétés Session.SetTimeout (60000); // 设置 Timeout 时间 session.connect (); // 通过 Session 建立链接 Channel chan = session.Opennannel ("SFTP"); // 打开 sftp 通道 chan.connect (); // 建立 sftp 通道的连接 canal = (canauxftp) chan; } catch (exception e) {logger.error ("sftp 连接失败"); e.printStackTrace (); }} @Override public void downloadRemoteFile (String filepath) {if (stringUtils.endswith (filepath, "/") || stringUtils.endswith (filepath, file.separator)) {filepath = filepath.substring (0, filepath.length () - 1); } Fichier SaveFile = nouveau fichier (filepath); FileOutputStream output = null; try {if (savefile.exists ()) {return; } // 创建目标文件路径 if (! SaveFile.getParentFile (). Existant ()) {SaveFile.GetParentFile (). MkDirs (); } SaveFile.CreateEwFile (); // 文件所在目录 String Path = filePath.SubString (0, filepath.LastIndexof ("/")); if (! StringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commandant.islinux) {path = path + file.separator; } else {path = path + "/"; }} channel.cd (path); Channel.get (filepath, new FileOutputStream (SaveFile)); Logger.debug ("文件 :" + filepath + "____________________________________________ 下载成功!"); } catch (exception e) {logger.debug ("文件 :" + filepath + "____________________________________________ 下载失败!"); e.printStackTrace (); } enfin {ioutils.closequietly (sortie); }} @SuppressWarnings ("Unchecked") @Override public list <string> listremoteFilePath (String Path) {list <string> list = new ArrayList <string> (); Vector <lSentry> v = null; essayez {if (! stringUtils.endswith (path, "/") && stringUtils.endswith (path, file.separator)) {path = path + file.separator; } v = channel.ls (path); } catch (sftPException e) {e.printStackTrace (); } pour (lSentry lSentry: v) {if (list.size ()> = max) {break; } if (! ".". Equals (l Sentry.getFileName ()) &&! "..". equals (lSentry.getFileName ())) {sftPattrs attrs = l Sentry.getAttrs (); if (att.isdir ()) {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commandant.islinux) {path = path + file.separator; } else {path = path + "/"; }} list.addall (this.ListremoteFilePath (path + lSentry.getFileName ())); } else {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commandant.islinux) {path = path + file.separator; } else {path = path + "/"; }} Fichier SaveFile = new File (path + lSentry.getFileName ()); if (! SaveFile.exists ()) {list.add (path + lSentry.getFileName ()); }}}} liste de retour; } @Override public void CloseConnection () {try {if (channel! = Null) {channel.quit (); canal.disconnect (); } if (session! = null) {session.disconnect (); }} catch (exception e) {e.printStackTrace (); }} public session getSession () {return session; } public void setSession (session session) {this.Session = session; } public channelsftp getChannel () {return canal; } public void setChannel (canalsftp canal) {this.channel = canal; }}以上所述是小编给大家介绍的 sftp 和 ftp 根据配置远程服务器地址下载文件到当前服务 , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!