废话不多说 , 关键代码如下所示 :
Paket com.eastrobot.remote; importieren java.util.list; import Java.util.concurrent.executorService; import Java.util.concurrent.executors; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; com.eastrobot.util.propertiesutil; /** * full.zhang * * ftp/sftp 抽象方法类 * */public Abstract Class Fileremote {private statische endgültige Zeichenfolge ftp_mode = "ftp"; private statische endgültige String sftp_mode = "sftp"; öffentliche statische Streicher Ftproot; öffentlicher statischer String -Modus; öffentlicher statischer String -Host; öffentlicher statischer String -Benutzername; öffentliches statisches String -Passwort; öffentlicher statischer String -Port; private static fileremote client = null; // 最大一次性下载 50 个文件 öffentliches statisches int max = 50; private endgültige statische statische Logger = logFactory.getLog (fileremote.class); public static fileremote getInstance () {if (client == null) {ftproot = propertiesutil.getString ("Transfer.root"); modus = propertiesUtil.getString ("Transfer.mode"); Host = PropertiesUtil.getString ("Transfer.host"); ustertiesutil.getString ("Transfer.username"); password = propertiesutil.getString ("Transfer.Password"); port = propertiesutil.getString ("Transfer.port"); if (modus.equals (ftp_mode)) {client = new FileftPremote (); } else if (modus.equals (sftp_mode)) {client = new FilesftPremote (); }} return client; } / ** * 执行定时任务 * / public void prozess () {logger.debug ("---------------------------------------- 进入定时下载远程文件"); // 创建线程池 ExecutorService exec = Executors. exec.execute(new Runnable() { @Override public void run() { // 建立连接 initFtpInfo(host, port, username, password); // 远程服务所有源文件路径集合 List<String> listSourcePath = listRemoteFilePath(ftproot); if (listSourcePath.isEmpty()) { LOGGER.debug("____________________释放连接"); Client.CLOSECONNECTION (); }); exec.shutdown (); } / ** * 初始化连接 * * @param host * @param port * @param userername * @param password * @throws exception * @return * / public abstract void initftpinfo (String -Host, String -Port, String -Benutzername, String -Passwort); / ** * 下载远程服务下文件到本地服务 * * @param path * @return * @throws Exception */ public abstract void downloadremoteFile (String filepath); / ** * 获取远程服务下指定目录下的所有文件路径集合 (包含子目录下文件) * * @param path * @return */ public abstractlist <string> listremoteFilePath (String -Pfad); / ** * 释放连接 */ public abstract void Closeconnection (); } [Java] Sehen Sie sich einfach Copypackage com.eastrobot.remote an; Import Java.io.file; importieren java.io.fileoutputStream; importieren java.io.ioException; importieren java.io.outputstream; Import Java.util.ArrayList; importieren 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.commander; öffentliche KlassendateiftPremote erweitert fileremote {protected ftpclient ftpclient; private String coding = "utf-8"; privat boolean binaryTransfer = true; private endgültige statische statische Logger = logFactory.getLog (FileftPremote.class); @Override public void initftpinfo (String -Host, String -Port, String -Benutzername, String -Passwort) {try {// 构造一个 ftpclient 实例 ftpclient = new ftpclient (); // 设置字符集 ftpclient.setControlencoding (codieren); // 连接 ftp 服务器 ftpclient.connect (host, Stringutils.isnotblank (Port)? Integer.Valueof (Port): 21); // 连接后检测返回码来校验连接是否成功 int Reply = ftpclient.getreplycode (); if (ftpreply.ispositiveCompletion (Antwort)) {// 登陆到 ftp 服务器 if (ftpclient.login (Benutzername, Passwort)) {setFiletype (); } ftpclient.login (Benutzername, Passwort); } 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.bary_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); } Datei SaveFile = New Datei (FilePath); if (SaveFile.Exists ()) {return; } // 文件所在目录 String path = filepath.substring (0, filepath.lastindexof ("/")); if (! Stringutils.endswith (Pfad, "/") &&! Stringutils.endswith (Pfad, Datei.separator)) {if (commander.islinux) {path = path + file.sepelator; } else {path = path + "/"; }} OutputStream output = null; try {// 创建目标文件路径 if (! SaveFile.getParentFile (). exist ()) {SaveFile.getParentFile (). mkdirs (); } SaveFile.CreateNewFile (); // 转移到 ftp 服务器目录 ftpclient.ChangeworkingDirectory (Pfad); output = new FileOutputStream (SaveFile); ftpclient.retrieveFile (filepath, Ausgabe); } catch (ioException e) {logger.debug ("文件:" + filepath + "______________________ 下载失败!"); E. printstacktrace (); } endlich {logger.debug ("文件:" + filepath + "______________________ 下载成功!"); Ioutils.closequiet (Output); }} @Override publiclist <string> listremoteFilePath (String -Pfad) {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 wechseln = ftpclient.ChangeWorkingDirectory (Pfad); if (wechseln) {ftpclient.setControlencoding (codieren); Ftpfile [] files = ftpclient.listfiles (); für (ftpfile Datei: Dateien) {if (list.size ()> = max) {break; } if (file.isdirectory ()) {if (! Stringutils.endswith (path, "/") &&! Stringutils.endswith (Pfad, Datei.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} list.addall (this.listemoteFilePath (path + file.getName ())); } else if (verändert) {if (! Stringutils.endswith (path, "/") &&! Stringutils.endswith (path, Datei.Sesparator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} Datei SaveFile = new Datei (path + file.getName ()); if (! SaveFile.Exists ()) {list.add (path + file.getName ()); }}}}} catch (Ausnahme e) {e.printstacktrace (); } Rückgabeliste; } @Override public void Closeconnection () {if (ftpclient! = Null) {try {ftpclient.Logout (); } catch (ioException e) {e.printstacktrace (); } endlich {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioException e) {e.printstacktrace (); }}}}}} [java] Sehen Sie sich einfach copypackage com.eastrobot.remote an; Import Java.io.file; importieren java.io.fileoutputStream; Import Java.util.ArrayList; importieren java.util.list; Import Java.util.Properties; Import 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.commander; 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; öffentliche Klasse filesftPremote erweitert Fileremote {Protected Session = NULL; geschützter Kanalsftp -Kanal = null; private endgültige statische statische Logger = logFactory.getLog (DateiftPremote.class); @Override public void initftpinfo (String -Host, String -Port, String -Benutzername, String -Passwort) {try {jsch jschsch = new jsch (); // 创建 JSCH 对象 Session = jsch.getSession (Benutzername, Host, Stringutils.isnotblank (Port)? Integer.ValueOf (Port): 22); Session.setPassword (Passwort); // 设置密码 Eigenschaften config = neue Eigenschaften (); config.put ("strikthostKeychecking", "no"); Session.setConfig (config); // 为 Sitzung 对象设置 Eigenschaften Sitzung.Settimeout (60000); // 设置 Timeout 时间 Session.connect (); // 通过 Sitzung 建立链接 Kanal chan = session.openchannel ("sftp"); // 打开 sftp 通道 chan.connect (); // 建立 SFTP 通道的连接 Channel = (Channelsftp) Chan; } catch (Ausnahme 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); } Datei SaveFile = New Datei (FilePath); FileOutputStream output = null; try {if (saveFile.exists ()) {return; } // 创建目标文件路径 if (! SaveFile.getParentFile (). Exist ()) {SaveFile.getParentFile (). Mkdirs (); } SaveFile.CreateNewFile (); // 文件所在目录 String path = filepath.substring (0, filepath.lastindexof ("/")); if (! Stringutils.endswith (Pfad, "/") &&! Stringutils.endswith (Pfad, Datei.separator)) {if (commander.islinux) {path = path + file.sepelator; } else {path = path + "/"; }} Channel.cd (Path); Channel.get (FilePath, New FileOutputStream (SaveFile)); Logger.debug ("文件 : :" + filepath + "________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ } catch (Ausnahme e) {logger.debug ("文件 :" + filepath + "____________________________________________ 下载失败!"); E. printstacktrace (); } endlich {ioutils.closequiet (output); }} @SuppressWarnings ("Deaktiviert") @Override publiclist <string> listremoteFilePath (String -Pfad) {list <string> list = new ArrayList <string> (); Vektor <lsentry> v = null; try {if (! stringutils.endswith (path, "/") && stringutils.endswith (path, file.separator)) {path = path + file.separator; } v = Channel.ls (Pfad); } catch (sftpexception e) {e.printstacktrace (); } für (lsentry lsentry: v) {if (list.size ()> = max) {break; } if (! ".". Equals (lsentry.getFileName ()) &&! if (attr.isdir ()) {if (! Stringutils.endswith (path, "/") &&! Stringutils.endswith (Pfad, Datei.Sesparator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} list.addall (this.listremoteFilePath (Pfad + lsentry.getFileName ())); } else {if (! Stringutils.endswith (path, "/") &&! Stringutils.endswith (Pfad, Datei.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} Datei SaveFile = neue Datei (Pfad + lsentry.getFileName ()); if (! SaveFile.Exists ()) {list.add (Pfad + lsentry.getFileName ()); }}}} Rückgabeliste; } @Override public void Closeconnection () {try {if (sender! = Null) {Channel.quit (); Channel.Disconnect (); } if (session! = null) {session.disconnect (); }} catch (Ausnahme e) {e.printstacktrace (); }} öffentliche Sitzung getSession () {return session; } public void setSession (Sitzungssitzung) {this.Session = Sitzung; } public Channelsftp getChannel () {return Channel; } public void setChannel (Channelftp -Kanal) {this.channel = Channel; }}以上所述是小编给大家介绍的 sftp 和 ftp 根据配置远程服务器地址下载文件到当前服务 , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持! 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!