废话不多说 , : :
пакет com.estrobot.remote; импортировать java.util.list; импортировать java.util.concurrent.executorservice; импортировать java.util.concurrent.executors; Импорт org.apache.commons.logging.log; Импорт org.apache.commons.logging.logfactory; Импорт com.estrobot.util.propertiesutil; /** * full.zhang * * ftp/sftp 抽象方法类 * */public abstract class fileremote {частная статическая конечная строка ftp_mode = "ftp"; частная статическая конечная строка sftp_mode = "sftp"; общественная статическая строка ftproot; публичный статический строковый режим; Общественный статический хост строк; Общественное статическое имя пользователя; Public Static String Password; Общественный статический строковый порт; Частный статический клиент FilereMote = null; // 最大一次性下载 50 个文件 Public Static int max = 50; Private Final Static Log Logger = logfactory.getLog (filereMote.class); public static fileremote getInstance () {if (client == null) {ftproot = propertiesutil.getString ("transfer.root"); mode = propertiesutil.getString ("transfer.mode"); host = propertiesutil.getstring ("transfer.host"); username = propertiesutil.getString ("transfer.username"); пароль = propertieSutil.getString ("transform.password"); port = propertiesutil.getString ("transfer.port"); if (mode.equals (ftp_mode)) {client = new fileftpremote (); } else if (mode.equals (sftp_mode)) {client = new filesftpremote (); }} вернуть клиент; } / ** * 执行定时任务 * / public void process () {logger.debug ("---------------------------------------- 进入定时下载远程文件"); // 创建线程池 ExecutorService exec = executors.newsingleThreadExeCutor (); exec.execute (new Runnable () {@override public void run () {// 建立连接 initftpinfo (хост, порт, имя пользователя, пароль); // 远程服务所有源文件路径集合 List <string> listsourcepath = listremotefilepath (ftproot); if (listsourcepath.isempty ()) {logger.debug ("________________________________________________________________________. client.colosenect (); exec.shutdown (); } / ** * 初始化连接 * * @param host * @param port * @param username * @param password * @throhs exception * @return * / public abstract void initftpinfo (string host, string port, string username, string password); / ** * 下载远程服务下文件到本地服务 * * @param path * @return * @throws Exception */ public rable void Downloadfile (String filePath); / ** * 获取远程服务下指定目录下的所有文件路径集合 (包含子目录下文件) * * @param path * @return */ public абстрактный список <string> listremotefilePath (String Path); / ** * 释放连接 */ public rable void closeconnection (); } [java] Посмотреть простые copypackage com.estrobot.remote; Импорт java.io.file; Импорт java.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; Import org.apache.commons.net.ftp.ftpclient; Import org.apache.commons.net.ftp.ftpfile; Импорт org.apache.commons.net.ftp.ftpreply; Импорт com.estrobot.command.commander; public class fileftpremote extends fileremote {protected ftpclient ftpclient; частная строка Encoding = "UTF-8"; Частный логический BinaryTransfer = true; Private Final Static Log Logger = logfactory.getLog (fileftPremote.class); @Override public void initftpinfo (string host, string port, string username, string password) {try {// 构造一个 ftpclient 实例 ftpclient = new ftpclient (); // 设置字符集 ftpclient.setControLencoding (кодирование); // 连接 ftp 服务器 ftpclient.connect (host, stringutils.isnotblank (порт)? Integer.valueof (порт): 21); // 连接后检测返回码来校验连接是否成功 int response = ftpclient.getReplyCode (); if (ftpreply.ispositivecoplusion (reply)) {// 登陆到 ftp 服务器 if (ftpclient.login (username, password)) {setFileType (); } ftpclient.login (имя пользователя, пароль); } 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); } Файл saveFile = новый файл (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; try {// 创建目标文件路径 if (! savefile.getParentFile (). существует ()) {saveFile.getParentFile (). mkdirs (); } saveFile.creatEnewFile (); // 转移到 ftp 服务器目录 ftpclient.changeworkingDirectory (path); output = new FileOutputStream (saveFile); ftpclient.retrievefile (filePath, выход); } 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> (); try {if (! stringUtils.endswith (path, "/") &&! StringUtils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} boolean mediceIR = ftpClient.ChangeWorkingDirectory (path); if (mediceir) {ftpclient.setControLencoDing (кодирование); Ftpfile [] files = ftpclient.listfiles (); for (ftpfile file: files) {if (list.size ()> = max) {break; } if (file.isdirectory ()) {if (! stringUtils.endswith (path, "/") &&! StringUtils.endswith (path, file.separator)) {if (commander.islinux) {path = pate + file.separator; } else {path = path + "/"; }} list.addall (this.listremotefilePath (path + file.getName ())); } else if (mediceir) {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commander.islinux) {path = pail + file.separator; } else {path = path + "/"; }} Файл saveFile = new File (path + file.getName ()); if (! savefile.exists ()) {list.add (path + file.getName ()); }}}}} catch (Exception e) {e.printstacktrace (); } return List; } @Override public void closeConnection () {if (ftpclient! = Null) {try {ftpclient.logout (); } catch (ioException e) {e.printstackTrace (); } наконец {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioException e) {e.printstackTrace (); }}}}}} [java] Просмотр простых copypackage com.estrobot.remote; Импорт java.io.file; Импорт java.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.estrobot.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 filesftpremote extends fileremote {защищенный сеанс сеанса = null; Защищенный канал канала = null; Private Final Static Log Logger = logfactory.getLog (filesftPremote.class); @Override public void initftpinfo (string host, string port, string username, string password) {try {jsch jsch = new jsch (); // 创建 jsch 对象 session = jsch.getSession (имя пользователя, хост, stringutils.isnotblank (порт)? Integer.valueof (port): 22); session.setpassword (пароль); // 设置密码 Свойства config = new Properties (); config.put («StricthostKeyChecking», «Нет»); session.setConfig (config); // 为 SESSION 对象设置 СЕБЕРСИЯ СЕБЕНИКА.SETTIMEOUT (60000); // 设置 Тайм -аут 时间 session.connect (); // 通过 Session 建立链接 Channel Chan = session.openchannel ("sftp"); // 打开 sftp 通道 chan.connect (); // 建立 sftp 通道的连接 channel = (canelelsftp) 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); } Файл saveFile = новый файл (filePath); FileOutputStream output = null; try {if (savefile.exists ()) {return; } // 创建目标文件路径 if (! Savefile.getParentFile (). Существует ()) {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 + "/"; }} channel.cd (path); channel.get (filepath, new FileOutputStream (saveFile)); Logger.debug ("文件 :" + filepath + "________________________________________________ 下载成功!"); } catch (Exception e) {logger.debug ("文件 :" + filePath + "____________________________________________________ 下载失败!"); e.printstacktrace (); } наконец {ioutils.closequietly (output); }} @Suppresswarnings ("unchecked") @override public list <string> listremotefilePath (String Path) {list <string> list = new ArrayList <string> (); Vector <lsentry> v = null; try {if (! stringutils.endswith (path, "/") && stringutils.endswith (path, file.separator)) {path = path + file.separator; } v = channel.ls (path); } catch (sftpexception e) {e.printstacktrace (); } for (lsentry lsentry: v) {if (list.size ()> = max) {break; } if (! ".". if (attrs.isdir ()) {if (! stringUtils.endswith (path, "/") &&! stringUtils.endswith (path, file.separator)) {if (commander.islinux) {path = pate + 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 + "/"; }} Файл saveFile = new File (path + lsentry.getFilename ()); if (! savefile.exists ()) {list.add (path + lsentry.getfilename ()); }}}} return List; } @Override public void closeConnection () {try {if (channel! = Null) {channel.quit (); channel.disconnect (); } if (session! = null) {session.disconnect (); }} catch (Exception e) {e.printstackTrace (); }} public session getSession () {return session; } public void setSession (сеанс сеанса) {this.session = session; } public Channelsftp getChannel () {return Channel; } public void setChannel (канал ChannelsFTP) {this.Channel = Channel; }}以上所述是小编给大家介绍的 sftp 和 ftp 根据配置远程服务器地址下载文件到当前服务 , 希望对大家有所帮助 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持! 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!