废话不多说 废话不多说, 关键代码如下所示 :
패키지 com.eastrobot.remote; Java.util.list 가져 오기; import java.util.concurrent.executorservice; java.util.concurrent.executors import; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; import com.eastrobot.util.propertiesutil; /** * full.zhang * * ftp/sftp 抽象方法类 * */public acblack class fileremote {private static final String ftp_mode = "ftp"; 개인 정적 최종 문자열 sftp_mode = "sftp"; 공개 정적 문자열 ftproot; 공개 정적 문자열 모드; 공개 정적 문자열 호스트; 공개 정적 문자열 사용자 이름; 공개 정적 문자열 비밀번호; 공개 정적 문자열 포트; 개인 정적 Fileremote 클라이언트 = NULL; // 最大一次性下载 50 最大一次性下载 공개 정적 int max = 50; 개인 최종 정적 로그 로거 = logfactory.getLog (fileremote.class); public static fileremote getInstance () {if (client == null) {ftproot = propertiesUtil.getString ( "송신 .Root"); mode = propertiesUtil.getString ( "송환. 모드"); host = propertiesutil.getString ( "송환. 호스트"); username = propertiesUtil.getString ( "송신 .username"); password = propertiesUtil.getString ( "송신. password"); port = propertiesutil.getString ( "송환. 포트"); 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 (호스트, 포트, 사용자 이름, 암호); // 远程服务所有源文件路径集合 listsourcepath = listremotefilepath (ftproot); if (listsourceath.isempty ()) {____________}; Client.CloseConce는 (ListSourCepath.SURCECATH.SURCEPATH.SURCERCEATH) exec.shutdown (); } / ** * * * @param host * @param port * @param username * @param password * @throws exception * @return * / public acpract void initftpinfo (문자열 호스트, 문자열 포트, 문자열 사용자 이름, 문자열 암호); / ** * * * * @param path * @return * @throws 예외 */ public acpract void downloadRemoteFile (String FilePath); / ** * 获取远程服务下指定目录下的所有文件路径集合 (包含子目录下文件 获取远程服务下指定目录下的所有文件路径集合) * * @param path * @return */ public acpract list <string> listremotefilepath (문자열 path); / ** * 释放连接 */ public Abstract void closeConnection (); } [java] 평면도 CopyPackage com.eastrobot.remote; import java.io.file; import java.io.fileoutputStream; import java.io.ioexception; import java.io.outputStream; java.util.arraylist 가져 오기; 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; com.eastrobot.command.commander import; 공개 클래스 FileftPremote 확장 Fileremote {Protected Ftpclient ftpclient; 개인 문자열 인코딩 = "UTF-8"; Private Boolean BinaryTransfer = true; 개인 최종 정적 로그 로거 = logfactory.getLog (fileftPremote.class); @override public void initftpinfo (문자열 호스트, 문자열 포트, 문자열 사용자 이름, 문자열 비밀번호) {try {// 构造一个 ftpclient 实例 ftpclient = new ftpclient (); // 设置字符集 ftpclient.setcontrolencoding (인코딩); // ftp 服务器 ftpclient.connect (호스트, StringUtils.isnotblank (port)? integer.valueof (port) : 21); // int reply = ftpclient.getReplyCode (); if (ftpReply.ispositiveCompletion (Reply)) {// 登陆到 ftp 服务器 if (ftpclient.login (username, password)) {setfileType (); } ftpclient.login (사용자 이름, 암호); } else {ftpclient.disconnect (); logger.error ( "ftp 服务拒绝连接!"); }} catch (예외 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 downloadDodlodRemoteFile (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 (! stringUtil.endswith (Path, "/") &&! stringUtil.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} outputStream output = null; try {// / if (! savefile.getParentFile (). } savefile.createnewfile (); // ftp 服务器目录 ftpclient.changeworkingDirectory (Path); output = 새 FileOutputStream (SaveFile); ftpclient.retrievefile (Filepath, 출력); } catch (ioexception e) {logger.debug ( "文件 :" + filepath + "______________________ 下载失败!"); e.printstacktrace (); } 마침내 {logger.debug ( "文件 :" + filepath + "______________________ 下载成功!"); ioutils.closequietly (출력); }} @override public list <string> listremotefilepath (문자열 path) {list <string> list = new arraylist <string> (); {if (! stringUtil.endswith (path, "/") &&! stringUtilsswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} boolean changeir = ftpclient.changeworkingDirectory (Path); if (changeir) {ftpclient.setcontrolencoding (인코딩); ftpfile [] files = ftpclient.listfiles (); for (ftpfile 파일 : files) {if (list.size ()> = max) {break; } if (file.isdirectory ()) {if (! stringUtil.endswith (path, "/") &&! stringUtilsswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} list.addall (this.listremoteFilePath (path + file.getName ())); } else if (changeir) {if (! stringUtils.endswith (path, "/") &&! stringUtil.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} 파일 savefile = 새 파일 (path + file.getName ()); if (! savefile.exists ()) {list.add (path + file.getName ()); }}}}} catch (예외 e) {e.printstacktrace (); } 반환 목록; } @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.eastrobot.remote; import java.io.file; import java.io.fileoutputStream; java.util.arraylist 가져 오기; Java.util.list 가져 오기; java.util.properties import; 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; com.eastrobot.command.commander import; import com.jcraft.jsch.channel; import com.jcraft.jsch.channelsftp; import com.jcraft.jsch.jsch; com.jcraft.jsch.session 가져 오기; com.jcraft.jsch.sftpattrs 가져 오기; import com.jcraft.jsch.sftpexception; import com.jcraft.jsch.channelsftp.lsentry; public class filesftPremote는 fileremote {Protected Session Session = null; 보호 된 Channelsftp 채널 = null; 개인 최종 정적 로그 로거 = logfactory.getLog (filesftPremote.class); @override public void initftpinfo (문자열 호스트, 문자열 포트, 문자열 사용자 이름, 문자열 비밀번호) {try {jsch jsch = new jsch (); // 创建 jsch 对象 세션 = jsch.getSession (username, host, stringUtils.isnotblank (port)? integer.valueof (port) : 22); 세션 .setpassword (비밀번호); // 设置密码 속성 config = new Properties (); config.put ( "stricthostkeyChecking", "no"); session.setConfig (config); // 为 세션 为 속성 세션 .settimeout (60000); // 设置 타임 아웃 设置 session.connect (); // 通过 세션 通过 채널 chan = session.openchannel ( "sftp"); // sftp 通道 chan.connect (); // sftp 通道的连接 채널 = (channelsftp) chan; } catch (예외 e) {logger.error ( "sftp 连接失败"); e.printstacktrace (); }} @override public void downloadDodlodRemoteFile (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.createnewfile (); // string path = filepath.substring (0, filepath.lastindexof ( "/")); if (! stringUtil.endswith (Path, "/") &&! stringUtil.endswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} channel.cd (경로); channel.get (filepath, 새 FileOutputStream (savefile)); logger.debug ( "文件 :" + filepath + "________________________________________ 下载成功!"); } catch (예외 e) {logger.debug ( "文件 :" + filepath + "__________________________________________________________________ 下载失败!"); e.printstacktrace (); } 마침내 {ioutils.closequietly (출력); }}} @suppresswarnings ( "선택 취소") @override public list <string> listremotefilepath (문자열 path) {list <string> list = new arraylist <string> (); 벡터 <lsentry> v = null; {if (! stringUtilsswith (path, "/") && stringUtil.endSwith (path, file.separator)) {path = path + file.separator; } v = channel.ls (경로); } catch (sftpexception e) {e.printstacktrace (); } for (lsentry lsentry : v) {if (list.size ()> = max) {break; } if (! ".". equals (lsentry.getfilename ()) &&! "..". if (atts.isdir ()) {if (! stringUtils.endswith (path, "/") &&! stringUtilsswith (path, file.separator)) {if (commander.islinux) {path = path + file.separator; } else {path = path + "/"; }} list.addall (this.listremotefilepath (path + lsentry.getfilename ())); } else {else {if (! stringUtils.endswith (Path, "/") &&! stringUtil.endSwith (path, file.separator)) {if (mainder.islinux) {path = path + file.separator; } else {path = path + "/"; }} 파일 savefile = 새 파일 (path + lsentry.getfilename ()); if (! savefile.exists ()) {list.add (path + lsentry.getfilename ()); }}}} 리턴 목록; } @override public void closeConnection () {try {if (channel! = null) {channel.quit (); channel.disconnect (); } if (session! = null) {session.disconnect (); }} catch (예외 e) {e.printstacktrace (); }} public session getsession () {반환 세션; } public void setsession (세션 세션) {this.session = 세션; } public channelsftp getChannel () {return 채널; } public void setChannel (channelsftp 채널) {this.channel = 채널; }}以上所述是小编给大家介绍的 sftp p ftp 根据配置远程服务器地址下载文件到当前服务 根据配置远程服务器地址下载文件到当前服务, 希望对大家有所帮助, 如果大家有任何疑问请给我留言, 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持! 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!