废话不多说 , 关键代码如下所示:
pacote com.eastrobot.remote; importar java.util.list; importar java.util.concurrent.executorService; importar java.util.concurrent.executores; importar org.apache.commons.logging.log; importar org.apache.commons.logging.logfactory; importação com.eastrobot.util.propertiesutil; /** * Full.zhang * * ftp/sftp 抽象方法类 * */public abstract class fileremote {private static final string ftp_mode = "ftp"; String final estática privada sftp_mode = "sftp"; public Static String ftProot; Modo de string estática pública; host público de string estática; Nome de usuário de string estática pública; senha pública de string estática; porta de sequência estática pública; cliente estático privado cliente = nulo; // 最大一次性下载 50 个文件 public static int max = 50; Logger estático final privado = logFactory.getLog (fileRemote.class); public static fileRemote getInstance () {if (client == null) {ftProot = PropertiesUtil.getString ("transfer.root"); mode = propertiesUtil.getString ("transfer.mode"); host = Propriedadesutil.getString ("transfer.host"); nome de usuário = propertiesutil.getString ("transfer.username"); senha = Propriedadesutil.getString ("transfer.password"); porta = propertiesutil.getString ("transfer.port"); if (mode.equals (ftp_mode)) {client = new FileftPremote (); } else if (mode.equals (sftp_mode)) {client = new filesftPremote (); }} retornar cliente; } / ** * 执行定时任务 * / public void Process () {Logger.debug ("-------------------------------------- 进入定时下载远程文件"); // 创建线程池 ExecutorService Exec = executores.NewsingleThreadExecutor (); EXEC.EXECUTE (new Runnable () {@Override public void run () {// 建立连接 initftpinfo (host, porta, nome de usuário, senha); // 远程服务所有源文件路径集合 list <string> listsourcepath = listremoteFilePath (ftProot); if (listsourcepath. () {) {Logger.B (ftProot); if (listsourcepath. " closé. exec.shutdown (); } / ** * 初始化连接 * * @param host * @param porta * @param nome de usuário * @param senha * @throws Exceção * @return * / public abstrate void initftpinfo (string host, porta string, string userName, string senha); / ** * 下载远程服务下文件到本地服务 * * @param caminho * @return * @throws Exception */ public Resumo void DownloadRemoteFile (String filepath); / ** * 获取远程服务下指定目录下的所有文件路径集合 (包含子目录下文件) * * @Param Path * @return */ list public abstrate <String> listremoteFilePath (caminho da string); / ** * 释放连接 */ Public Resumo void Closeconnection (); } [java] Exibir copypackage simples com.eastrobot.remote; importar java.io.file; importar java.io.fileOutputStream; importar java.io.ioException; importar java.io.OutputStream; importar java.util.arraylist; importar java.util.list; importar org.apache.commons.io.ioutils; importar org.apache.commons.lang.stringutils; importar org.apache.commons.logging.log; importar org.apache.commons.logging.logfactory; importar org.apache.commons.net.ftp.ftpClient; importar org.apache.commons.net.ftp.ftpfile; importar org.apache.commons.net.ftp.ftpreply; importação com.eastrobot.command.commander; classe pública fileftpremote estende o fileRemote {ftpClient ftpClient protegido; private string coding = "utf-8"; Binary BinaryTransfer privado = true; Logger estático final privado = logFactory.getLog (fileftpremote.class); @Override public void initftpinfo (host de string, porta string, string userName, string senha) {try {// 构造一个 ftpClient 实例 ftpClient = new ftpClient (); // 设置字符集 ftpClient.SetControlencoding (codificação); // 连接 ftp 服务器 ftpClient.Connect (host, stringUtils.isnotblank (porta)? Integer.valueof (porta): 21); // 连接后检测返回码来校验连接是否成功 int Responder = ftpClient.getReplyCode (); if (ftpreply.ispositiveciction (resposta)) {// 登陆到 ftp 服务器 if (ftpClient.login (nome de usuário, senha)) {setFileType (); } ftpclient.login (nome de usuário, senha); } else {ftpclient.disconnect (); Logger.error ("ftp 服务拒绝连接!"); }} catch (Exceção 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, filePaparator)) {filepath = filepath.substring (0, filepath.Length () - 1); } Arquivo savefile = novo arquivo (filepath); if (savefile.exists ()) {return; } // 文件所在目录 String PATH = FILEPATH.SUBSTRING (0, FILEPATH.LASTIndexOf ("/")); if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} OutputStream Output = null; tente {// 创建目标文件路径 if (! savefile.getparentfile (). exist ()) {savefile.getparentfile (). mkdirs (); } savefile.createNewFile (); // 转移到 ftp 服务器目录 ftpClient.ChangeWorkingDirectory (caminho); output = new FileOutputStream (savefile); ftpClient.retrievefile (filepath, saída); } catch (ioexception e) {logger.debug ("文件:" + filepath + "______________________ 下载失败!"); E.PrintStackTrace (); } finalmente {logger.debug ("文件:" + filepath + "______________________ 下载成功!"); Ioutils.CloseQuietly (saída); }} @Override Public List <String> listremoteFilePath (String Path) {List <String> list = new ArrayList <String> (); tente {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} boolean alterado = ftpClient.ChangeWorkingDirectory (caminho); if (alterado) {ftpClient.SetControlEncoding (codificação); Ftpfile [] arquivos = ftpClient.ListFiles (); para (arquivo ftpfile: arquivos) {if (list.size ()> = max) {break; } if (file.isdirectory ()) {if (! stringUtils.endswith (path, "/") &&! stringItils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} list.addall (this.listremoteFilePath (path + file.getName ())); } else if (alteração) {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} Arquivo savefile = new File (caminho + file.getName ()); if (! savefile.exists ()) {list.add (path + file.getName ()); }}}}} catch (Exceção e) {e.printStackTrace (); } Lista de retorno; } @Override public void ClosConnection () {if (ftpClient! = Null) {try {ftpclient.logout (); } catch (ioexception e) {e.printStackTrace (); } finalmente {if (ftpClient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioexception e) {e.printStackTrace (); }}}}}} [java] Veja o copypackage simples com.eastrobot.remote; importar java.io.file; importar java.io.fileOutputStream; importar java.util.arraylist; importar java.util.list; importar java.util.properties; importar java.util.Vector; importar org.apache.commons.io.ioutils; importar org.apache.commons.lang.stringutils; importar org.apache.commons.logging.log; importar org.apache.commons.logging.logfactory; importação com.eastrobot.command.commander; importação com.jcraft.jsch.channel; import com.jcraft.jsch.channelsftp; importação com.jcraft.jsch.jsch; importação com.jcraft.jsch.session; importação com.jcraft.jsch.sftpattrs; import com.jcraft.jsch.sftPexception; import com.jcraft.jsch.channelsftp.lsentry; classe pública filesftPremote estende o fileRemote {sessão protegida session = null; canalsftp protegido canal = null; Logger estático final privado = logFactory.getLog (filesftpremote.class); @Override public void initftpinfo (host de string, porta string, string userName, string senha) {try {jsch jsch = new jsch (); // 创建 JSCH 对象 Sessão = jsch.getSession (nome de usuário, host, stringUtils.isnotblank (porta)? Integer.valueof (porta): 22); session.setPassword (senha); // 设置密码 Propriedades config = new Properties (); config.put ("stricthostkeychecking", "não"); session.setConfig (config); // 为 Sessão 对象设置 Propriedades session.setTimeout (60000); // timeout 时间 session.connect (); // 通过 Sessão 建立链接 canal chan = session.openchannel ("sftp"); // 打开 sftp 通道 chan.connect (); // 建立 sftp 通道的连接 canal = (canaisftp) chan; } catch (Exceção e) {Logger.error ("sftp 连接失败"); E.PrintStackTrace (); }} @Override public void DownloadRemoteFile (string filepath) {if (stringUtils.endswith (filepath, "/") || stringUtils.endswith (filepath, filePaparator)) {filepath = filepath.substring (0, filepath.Length () - 1); } Arquivo savefile = novo arquivo (filepath); FileOutputStream Output = NULL; tente {if (savefile.exists ()) {return; } // 创建目标文件路径 if (! Savefile.getparentfile (). Exist ()) {savefile.getParentFile (). Mkdirs (); } savefile.createNewFile (); // 文件所在目录 String Path = filepath.substring (0, filepath.LastIndexOf ("/")); if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} canal.cd (caminho); canal.get (filepath, new FileOutputStream (savefile)); Logger.debug ("文件 :" + filepath + "____________________________________________ 下载成功!"); } catch (Exceção e) {Logger.debug ("文件 ::" + filepath + "____________________________________________ 下载失败!"); E.PrintStackTrace (); } finalmente {ioutils.closeQuietly (saída); }} @Suppresswarnings ("desmarcado") @Override Public List <String> listremoteFilePath (String Path) {List <String> list = new ArrayList <String> (); Vetor <lsentry> v = null; tente {if (! stringutils.endswith (path, "/") && stringiltils.endswith (path, file.separator)) {path = path = path + file.separator; } v = canal.ls (caminho); } catch (sftPexception e) {e.printStackTrace (); } para (lSentry lSentry: v) {if (list.size ()> = max) {break; } if (! ".". Equals (lSentry.getFilename ()) &&! "..". Equals (lSentry.getFilename ())) {sftpattrs attrs = lSentry.getAtTrs (); if (attrs.isdir ()) {if (! stringUtils.endswith (path, "/") &&! stringils.endswith (path, file.separator)) {if (commander.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 (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} Arquivo savefile = novo arquivo (caminho + lsentry.getFilename ()); if (! savefile.exists ()) {list.add (path + lsentry.getfilename ()); }}}} Lista de retorno; } @Override public void ClosConnection () {try {if (canal! = Null) {Channel.quit (); canal.disconnect (); } if (session! = null) {session.disconnect (); }} catch (Exceção e) {e.printStackTrace (); }} public session getSession () {retorna sessão; } public void SetSession (Sessão) {this.Session = Session; } public Channelsftp getChannel () {retornar canal; } public void setChannel (canal canalfftp) {this.channel = canal; }}以上所述是小编给大家介绍的 sftp 和 ftp 根据配置远程服务器地址下载文件到当前服务 , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!