欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

sftp和ftp 根据配置远程服务器地址下载文件到当前服务

程序员文章站 2024-03-11 22:46:19
废话不多说,关键代码如下所示:   package com.eastrobot.remote; import java.util.list;...

废话不多说,关键代码如下所示:

 

package com.eastrobot.remote; 
import 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; 
import com.eastrobot.util.propertiesutil; 
/** 
* full.zhang 
* 
* ftp/sftp抽象方法类 
* 
*/ 
public abstract class fileremote { 
private static final string ftp_mode = "ftp"; 
private static final string sftp_mode = "sftp"; 
public static string ftproot; 
public static string mode; 
public static string host; 
public static string username; 
public static string password; 
public static string port; 
private static fileremote client = 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"); 
password = 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 filesftpremote(); 
} 
} 
return client; 
} 
/** 
* 执行定时任务 
*/ 
public void process() { 
logger.debug("----------------------------------------进入定时下载远程文件"); 
// 创建线程池 
executorservice exec = executors.newsinglethreadexecutor(); 
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(); 
return; 
} 
if (listsourcepath.size() > max) { 
listsourcepath = listsourcepath.sublist(0, max); 
} 
for (string path : listsourcepath) { 
downloadremotefile(path); 
} 
logger.debug("____________________释放连接"); 
client.closeconnection(); 
} 
}); 
exec.shutdown(); 
} 
/** 
* 初始化连接 
* 
* @param host 
* @param port 
* @param username 
* @param password 
* @throws exception 
* @return 
*/ 
public abstract void initftpinfo(string host, string port, string username, string password); 
/** 
* 下载远程服务下文件到本地服务 
* 
* @param path 
* @return 
* @throws exception 
*/ 
public abstract void downloadremotefile(string filepath); 
/** 
* 获取远程服务下指定目录下的所有文件路径集合(包含子目录下文件) 
* 
* @param path 
* @return 
*/ 
public abstract list<string> listremotefilepath(string path); 
/** 
* 释放连接 
*/ 
public abstract void closeconnection(); 
} 
[java] view plain copy
package com.eastrobot.remote; 
import java.io.file; 
import java.io.fileoutputstream; 
import java.io.ioexception; 
import java.io.outputstream; 
import java.util.arraylist; 
import 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; 
public class fileftpremote extends fileremote { 
protected ftpclient ftpclient; 
private string encoding = "utf-8"; 
private boolean 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(encoding); 
// 连接ftp服务器 
ftpclient.connect(host, stringutils.isnotblank(port) ? integer.valueof(port) : 21); 
// 连接后检测返回码来校验连接是否成功 
int reply = ftpclient.getreplycode(); 
if (ftpreply.ispositivecompletion(reply)) { 
// 登陆到ftp服务器 
if (ftpclient.login(username, password)) { 
setfiletype(); 
} 
ftpclient.login(username, password); 
} 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); 
} 
file savefile = new file(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().exists()) { 
savefile.getparentfile().mkdirs(); 
} 
savefile.createnewfile(); 
// 转移到ftp服务器目录 
ftpclient.changeworkingdirectory(path); 
output = new fileoutputstream(savefile); 
ftpclient.retrievefile(filepath, output); 
} catch (ioexception e) { 
logger.debug("文件:" + filepath + "______________________下载失败!"); 
e.printstacktrace(); 
} finally { 
logger.debug("文件:" + filepath + "______________________下载成功!"); 
ioutils.closequietly(output); 
} 
} 
@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 changedir = ftpclient.changeworkingdirectory(path); 
if (changedir) { 
ftpclient.setcontrolencoding(encoding); 
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 = path + file.separator; 
} else { 
path = path + "/"; 
} 
} 
list.addall(this.listremotefilepath(path + file.getname())); 
} else if (changedir) { 
if (!stringutils.endswith(path, "/") && !stringutils.endswith(path, file.separator)) { 
if (commander.islinux) { 
path = path + file.separator; 
} else { 
path = path + "/"; 
} 
} 
file 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(); 
} finally { 
if (ftpclient.isconnected()) { 
try { 
ftpclient.disconnect(); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
} 
} 
} 
} 
} 
[java] view plain copy
package com.eastrobot.remote; 
import java.io.file; 
import java.io.fileoutputstream; 
import java.util.arraylist; 
import 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; 
public class filesftpremote extends fileremote { 
protected session session = null; 
protected channelsftp channel = 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(username, host, stringutils.isnotblank(port) ? integer.valueof(port) : 22); 
session.setpassword(password); // 设置密码 
properties config = new properties(); 
config.put("stricthostkeychecking", "no"); 
session.setconfig(config); // 为session对象设置properties 
session.settimeout(60000); // 设置timeout时间 
session.connect(); // 通过session建立链接 
channel 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, filepath.length() - 1); 
} 
file savefile = new file(filepath); 
fileoutputstream output = null; 
try { 
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, new fileoutputstream(savefile)); 
logger.debug("文件:" + filepath + "____________________________________________下载成功!"); 
} catch (exception e) { 
logger.debug("文件:" + filepath + "____________________________________________下载失败!"); 
e.printstacktrace(); 
} finally { 
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 (!".".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 = 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(session session) { 
this.session = session; 
} 
public channelsftp getchannel() { 
return channel; 
} 
public void setchannel(channelsftp channel) { 
this.channel = channel; 
} 
}

以上所述是小编给大家介绍的sftp和ftp 根据配置远程服务器地址下载文件到当前服务,希望对大家有所帮助