废话不多说 , : :
paket com.eastrobot.remote; impor java.util.list; impor java.util.concurrent.executorservice; impor java.util.concurrent.Executors; impor org.apache.commons.logging.log; impor org.apache.commons.logging.logfactory; impor com.eastrobot.util.propertiesutil; /** * full.zhang * * ftp/sftp 抽象方法类 * */kelas abstrak publik fileremote {private static final string ftp_mode = "ftp"; string final statis privat sftp_mode = "sftp"; string statis publik ftproT; mode string statis publik; host string statis publik; Nama pengguna string statis publik; kata sandi string statis publik; port string statis publik; klien fileremote statis pribadi = null; // 最大一次性下载 50 个文件 Public Static Int Max = 50; logger log statis final privat = logfactory.getLog (fileremote.class); public static fileremote getInstance () {if (client == null) {ftproT = propertiesutil.getString ("transfer.root"); mode = propertiesutil.getString ("transfer.mode"); host = propertiesutil.getString ("transfer.host"); UserName = propertiesutil.getString ("transfer.username"); kata sandi = 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 (); }} kembalikan klien; } / ** * 执行定时任务 * / proses public void () {logger.debug ("---------------------------------------- 进入定时下载远程文件"); // 创建线程池 ExecutorService exec = executors.newsinglethreadExecutor (); exec.execute (runnable baru () {@Override public void run () {// 建立连接 initftpinfo (host, port, nama pengguna, kata sandi); // 远程服务所有源文件路径集合 daftar <string> listsourcepath = listremoteFilePath (ftproot); if (listsourcePath.isempy () () {ftproTe); if (listSourcePath.isempy () () {ftproot); if (listSourcePath client.closeconnection (); }); exec.shutdown (); } / ** * 初始化连接 * * @param host * @param port * @param nama pengguna * @param kata sandi * @throws Exception * @return * / public abstrak void initftpinfo (host string, port string, string nama pengguna, string kata sandi); / ** * 下载远程服务下文件到本地服务 * * @param path * @return * @throws Exception */ public abstrak void downloadremoteFile (string filepath); / ** * 获取远程服务下指定目录下的所有文件路径集合 (包含子目录下文件) * * @param path * @return */ Daftar abstrak publik <string> listremotefilePath (string path); / ** * 释放连接 */ public abstrak void closeConnection (); } [java] Lihat copypackage polos com.eastrobot.remote; impor java.io.file; impor java.io.fileoutputStream; impor java.io.ioException; impor java.io.outputStream; impor java.util.arraylist; impor java.util.list; impor org.apache.commons.io.ioutils; impor org.apache.commons.lang.stringutils; impor org.apache.commons.logging.log; impor org.apache.commons.logging.logfactory; impor org.apache.commons.net.ftp.ftpclient; impor org.apache.commons.net.ftp.ftpfile; impor org.apache.commons.net.ftp.ftpreply; impor com.eastrobot.command.commander; kelas publik FileFtPremote memperluas fileremote {ftpClient ftpClient yang dilindungi; private string encoding = "UTF-8"; Private Boolean BinaryTransfer = true; logger log statis final privat = logfactory.getLog (fileftpremote.class); @Override public void initftpinfo (host string, port string, string nama pengguna, kata sandi string) {coba {// 构造一个 ftpClient 实例 ftpClient = ftpClient baru (); // 设置字符集 ftpClient.setControlencoding (encoding); // 连接 ftp 服务器 ftpclient.connect (host, stringutils.isnotblank (port)? Integer.valueof (port): 21); // 连接后检测返回码来校验连接是否成功 int Balas = ftpClient.getReplyCode (); if (ftpreply.ispositiveCompletion (balasan)) {// 登陆到 ftp 服务器 if (ftpclient.login (nama pengguna, kata sandi)) {setFileType (); } ftpclient.login (nama pengguna, kata sandi); } else {ftpclient.disconnect (); Logger.Error ("FTP 服务拒绝连接!"); }} catch (Exception e) {if (ftpclient.isconnected ()) {coba {ftpclient.disconnect (); // 断开连接} catch (ioException e1) {logger.error ("ftp 服务连接断开失败!"); }} Logger.Error ("ftp 服务连接失败!"); }} / ** * 设置文件传输类型 * / private void setFileType () {coba {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, filepator. } File saveFile = file baru (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; coba {// 创建目标文件路径 if (! saveFile.getParentFile (). Exists ()) {saveFile.getParentFile (). mkdirs (); } saveFile.createNewFile (); // 转移到 ftp 服务器目录 ftpclient.changeworkingdirectory (path); output = FileOutputStream baru (saveFile); ftpClient.retrievefile (filepath, output); } catch (ioException e) {logger.debug ("文件:" + filepath + "______________________ 下载失败!"); e.printstacktrace (); } akhirnya {logger.debug ("文件:" + filepath + "______________________ 下载成功!"); Ioutils.closequietly (output); }} @Override Daftar publik <string> listremoTeFilePath (string path) {list <string> list = new ArrayList <String> (); coba {if (! stringutils.endswith (path, "/") &&! stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} boolean changedir = ftpclient.changeworkingdirectory (path); if (ubah) {ftpclient.setControlencoding (encoding); Ftpfile [] file = ftpclient.listFiles (); untuk (file ftpfile: file) {if (list.size ()> = max) {break; } if (file.isDirectory ()) {if (! stringutils.endswith (path, "/") &&! stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} list.addall (this.listremoteFilePath (path + file.getName ())); } else if (ubah) {if (! stringutils.endswith (path, "/") &&! stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} File saveFile = file baru (path + file.getName ()); if (! saveFile.exists ()) {list.add (path + file.getName ()); }}}}} catch (Exception e) {E.PrintStackTrace (); } daftar pengembalian; } @Override public void closeConnection () {if (ftpClient! = Null) {coba {ftpclient.logout (); } catch (ioException e) {e.printstacktrace (); } akhirnya {if (ftpclient.isconnected ()) {coba {ftpclient.disconnect (); } catch (ioException e) {e.printstacktrace (); }}}}}} [java] Lihat copypackage biasa com.eastrobot.remote; impor java.io.file; impor java.io.fileoutputStream; impor java.util.arraylist; impor java.util.list; impor java.util.properties; impor java.util.vector; impor org.apache.commons.io.ioutils; impor org.apache.commons.lang.stringutils; impor org.apache.commons.logging.log; impor org.apache.commons.logging.logfactory; impor com.eastrobot.command.commander; impor com.jcraft.jsch.channel; impor com.jcraft.jsch.channelsftp; impor com.jcraft.jsch.jsch; impor com.jcraft.jsch.Session; impor com.jcraft.jsch.sftpattrs; impor com.jcraft.jsch.sftpexception; impor com.jcraft.jsch.channelsftp.lsentry; file kelas publikFtPremote memperluas filereMote {sides sesi protected = null; Saluran yang Dilindungi Saluran = NULL; logger log statis final privat = logfactory.getLog (fileftpremote.class); @Override public void initftpinfo (host string, port string, nama pengguna string, kata sandi string) {coba {jsch jsch = new jsch (); // 创建 jsch 对象 sesi = jsch.getSession (nama pengguna, host, stringutils.isnotblank (port)? Integer.valueof (port): 22); session.setPassword (kata sandi); // 设置密码 Properties Config = New Properties (); config.put ("StricthostKeyChecking", "no"); session.setConfig (config); // 为 Sesi 对象设置 Sesi Properti.SetTimeout (60000); // 设置 Batas waktu 时间 session.connect (); // 通过 sesi 建立链接 saluran chan = session.openchannel ("sftp"); // 打开 sftp 通道 chan.connect (); // 建立 sftp 通道的连接 channel = (channelsftp) 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, filepator. } File saveFile = file baru (filepath); FileOutputStream output = null; coba {if (saveFile.exists ()) {return; } // 创建目标文件路径 if (! SaveFile.getParentFile (). Exists ()) {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, FileOutputStream baru (saveFile)); Logger.debug ("文件 :" + filepath + "____________________________________________ 下载成功!"); } catch (Exception e) {logger.debug ("文件 :" + filepath + "____________________________________________ 下载失败!"); e.printstacktrace (); } akhirnya {ioutils.closequietly (output); }} @SuppressWarnings ("Uncecked") @Override Daftar publik <string> listremoTeFilePath (string path) {list <string> Daftar = ArrayList baru <string> (); Vektor <lsentry> v = null; coba {if (! stringutils.endswith (path, "/") && stringutils.endswith (path, file.separator)) {path = path + file.separator; } v = channel.ls (path); } catch (sftpException e) {e.printstacktrace (); } untuk (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, "/") &&! stringutils.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 + "/"; }} File saveFile = file baru (path + lsEntry.getFileName ()); if (! saveFile.exists ()) {list.add (path + lsentry.getFileName ()); }}}} daftar pengembalian; } @Override public void closeConnection () {coba {if (channel! = Null) {channel.quit (); channel.disconnect (); } if (session! = null) {session.disconnect (); }} catch (Exception e) {e.printstacktrace (); }} sesi publik getSession () {return sesi; } public void setSession (sesi sesi) {this.Session = sesi; } Public Channelsftp getChannel () {return channel; } public void setChannel (saluran channelsftp) {this.channel = channel; }}以上所述是小编给大家介绍的 sftp 和 ftp 根据配置远程服务器地址下载文件到当前服务 , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!