您好,欢迎访问一九零五行业门户网

详解JAVA SFTP文件上传,下载及批量下载的实例代码

本篇文章主要介绍了java sftp文件上传、下载及批量下载实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
1.jsch官方api查看地址(附件为需要的jar)
http://www.jcraft.com/jsch/
2.jsch简介
jsch(java secure channel)是一个ssh2的纯java实现。它允许你连接到一个ssh服务器,并且可以使用端口转发,x11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。
sftp(secure file transfer protocol)安全文件传送协议。可以为传输文件提供一种安全的加密方法。sftp 为 ssh的一部份,是一种传输文件到服务器的安全方式,但是传输效率比普通的ftp要低。
3.api常用的方法:
put():      文件上传
get():      文件下载
cd():       进入指定目录
ls():       得到指定目录下的文件列表
rename():   重命名指定文件或目录
rm():       删除指定文件
mkdir():    创建目录
rmdir():    删除目录
put和get都有多个重载方法,自己看源代码
4.对常用方法的使用,封装成一个util类
import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.util.arraylist; import java.util.iterator; import java.util.list; import java.util.properties; import java.util.vector; import org.apache.log4j.logger; 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; /** * sftp工具类 * * @author xxx * @date 2014-6-17 * @time 下午1:39:44 * @version 1.0 */ public class sftputils { private static logger log = logger.getlogger(sftputils.class.getname()); private string host;//服务器连接ip private string username;//用户名 private string password;//密码 private int port = 22;//端口号 private channelsftp sftp = null; private session sshsession = null; public sftputils(){} public sftputils(string host, int port, string username, string password) { this.host = host; this.username = username; this.password = password; this.port = port; } public sftputils(string host, string username, string password) { this.host = host; this.username = username; this.password = password; } /** * 通过sftp连接服务器 */ public void connect() { try { jsch jsch = new jsch(); jsch.getsession(username, host, port); sshsession = jsch.getsession(username, host, port); if (log.isinfoenabled()) { log.info("session created."); } sshsession.setpassword(password); properties sshconfig = new properties(); sshconfig.put("stricthostkeychecking", "no"); sshsession.setconfig(sshconfig); sshsession.connect(); if (log.isinfoenabled()) { log.info("session connected."); } channel channel = sshsession.openchannel("sftp"); channel.connect(); if (log.isinfoenabled()) { log.info("opening channel."); } sftp = (channelsftp) channel; if (log.isinfoenabled()) { log.info("connected to " + host + "."); } } catch (exception e) { e.printstacktrace(); } } /** * 关闭连接 */ public void disconnect() { if (this.sftp != null) { if (this.sftp.isconnected()) { this.sftp.disconnect(); if (log.isinfoenabled()) { log.info("sftp is closed already"); } } } if (this.sshsession != null) { if (this.sshsession.isconnected()) { this.sshsession.disconnect(); if (log.isinfoenabled()) { log.info("sshsession is closed already"); } } } } /** * 批量下载文件 * @param remotpath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/) * @param localpath:本地保存目录(以路径符号结束,d:\duansha\sftp\) * @param fileformat:下载文件格式(以特定字符开头,为空不做检验) * @param fileendformat:下载文件格式(文件格式) * @param del:下载后是否删除sftp文件 * @return */ public list<string> batchdownloadfile(string remotepath, string localpath, string fileformat, string fileendformat, boolean del) { list<string> filenames = new arraylist<string>(); try { // connect(); vector v = listfiles(remotepath); // sftp.cd(remotepath); if (v.size() > 0) { system.out.println("本次处理文件个数不为零,开始下载...filesize=" + v.size()); iterator it = v.iterator(); while (it.hasnext()) { lsentry entry = (lsentry) it.next(); string filename = entry.getfilename(); sftpattrs attrs = entry.getattrs(); if (!attrs.isdir()) { boolean flag = false; string localfilename = localpath + filename; fileformat = fileformat == null ? "" : fileformat .trim(); fileendformat = fileendformat == null ? "" : fileendformat.trim(); // 三种情况 if (fileformat.length() > 0 && fileendformat.length() > 0) { if (filename.startswith(fileformat) && filename.endswith(fileendformat)) { flag = downloadfile(remotepath, filename,localpath, filename); if (flag) { filenames.add(localfilename); if (flag && del) { deletesftp(remotepath, filename); } } } } else if (fileformat.length() > 0 && "".equals(fileendformat)) { if (filename.startswith(fileformat)) { flag = downloadfile(remotepath, filename, localpath, filename); if (flag) { filenames.add(localfilename); if (flag && del) { deletesftp(remotepath, filename); } } } } else if (fileendformat.length() > 0 && "".equals(fileformat)) { if (filename.endswith(fileendformat)) { flag = downloadfile(remotepath, filename,localpath, filename); if (flag) { filenames.add(localfilename); if (flag && del) { deletesftp(remotepath, filename); } } } } else { flag = downloadfile(remotepath, filename,localpath, filename); if (flag) { filenames.add(localfilename); if (flag && del) { deletesftp(remotepath, filename); } } } } } } if (log.isinfoenabled()) { log.info("download file is success:remotepath=" + remotepath + "and localpath=" + localpath + ",file size is" + v.size()); } } catch (sftpexception e) { e.printstacktrace(); } finally { // this.disconnect(); } return filenames; } /** * 下载单个文件 * @param remotpath:远程下载目录(以路径符号结束) * @param remotefilename:下载文件名 * @param localpath:本地保存目录(以路径符号结束) * @param localfilename:保存文件名 * @return */ public boolean downloadfile(string remotepath, string remotefilename,string localpath, string localfilename) { fileoutputstream fieloutput = null; try { // sftp.cd(remotepath); file file = new file(localpath + localfilename); // mkdirs(localpath + localfilename); fieloutput = new fileoutputstream(file); sftp.get(remotepath + remotefilename, fieloutput); if (log.isinfoenabled()) { log.info("===downloadfile:" + remotefilename + " success from sftp."); } return true; } catch (filenotfoundexception e) { e.printstacktrace(); } catch (sftpexception e) { e.printstacktrace(); } finally { if (null != fieloutput) { try { fieloutput.close(); } catch (ioexception e) { e.printstacktrace(); } } } return false; } /** * 上传单个文件 * @param remotepath:远程保存目录 * @param remotefilename:保存文件名 * @param localpath:本地上传目录(以路径符号结束) * @param localfilename:上传的文件名 * @return */ public boolean uploadfile(string remotepath, string remotefilename,string localpath, string localfilename) { fileinputstream in = null; try { createdir(remotepath); file file = new file(localpath + localfilename); in = new fileinputstream(file); sftp.put(in, remotefilename); return true; } catch (filenotfoundexception e) { e.printstacktrace(); } catch (sftpexception e) { e.printstacktrace(); } finally { if (in != null) { try { in.close(); } catch (ioexception e) { e.printstacktrace(); } } } return false; } /** * 批量上传文件 * @param remotepath:远程保存目录 * @param localpath:本地上传目录(以路径符号结束) * @param del:上传后是否删除本地文件 * @return */ public boolean bacthuploadfile(string remotepath, string localpath, boolean del) { try { connect(); file file = new file(localpath); file[] files = file.listfiles(); for (int i = 0; i < files.length; i++) { if (files[i].isfile() && files[i].getname().indexof("bak") == -1) { if (this.uploadfile(remotepath, files[i].getname(), localpath, files[i].getname()) && del) { deletefile(localpath + files[i].getname()); } } } if (log.isinfoenabled()) { log.info("upload file is success:remotepath=" + remotepath + "and localpath=" + localpath + ",file size is " + files.length); } return true; } catch (exception e) { e.printstacktrace(); } finally { this.disconnect(); } return false; } /** * 删除本地文件 * @param filepath * @return */ public boolean deletefile(string filepath) { file file = new file(filepath); if (!file.exists()) { return false; } if (!file.isfile()) { return false; } boolean rs = file.delete(); if (rs && log.isinfoenabled()) { log.info("delete file success from local."); } return rs; } /** * 创建目录 * @param createpath * @return */ public boolean createdir(string createpath) { try { if (isdirexist(createpath)) { this.sftp.cd(createpath); return true; } string patharry[] = createpath.split("/"); stringbuffer filepath = new stringbuffer("/"); for (string path : patharry) { if (path.equals("")) { continue; } filepath.append(path + "/"); if (isdirexist(filepath.tostring())) { sftp.cd(filepath.tostring()); } else { // 建立目录 sftp.mkdir(filepath.tostring()); // 进入并设置为当前目录 sftp.cd(filepath.tostring()); } } this.sftp.cd(createpath); return true; } catch (sftpexception e) { e.printstacktrace(); } return false; } /** * 判断目录是否存在 * @param directory * @return */ public boolean isdirexist(string directory) { boolean isdirexistflag = false; try { sftpattrs sftpattrs = sftp.lstat(directory); isdirexistflag = true; return sftpattrs.isdir(); } catch (exception e) { if (e.getmessage().tolowercase().equals("no such file")) { isdirexistflag = false; } } return isdirexistflag; } /** * 删除stfp文件 * @param directory:要删除文件所在目录 * @param deletefile:要删除的文件 * @param sftp */ public void deletesftp(string directory, string deletefile) { try { // sftp.cd(directory); sftp.rm(directory + deletefile); if (log.isinfoenabled()) { log.info("delete file success from sftp."); } } catch (exception e) { e.printstacktrace(); } } /** * 如果目录不存在就创建目录 * @param path */ public void mkdirs(string path) { file f = new file(path); string fs = f.getparent(); f = new file(fs); if (!f.exists()) { f.mkdirs(); } } /** * 列出目录下的文件 * * @param directory:要列出的目录 * @param sftp * @return * @throws sftpexception */ public vector listfiles(string directory) throws sftpexception { return sftp.ls(directory); } public string gethost() { return host; } public void sethost(string host) { this.host = host; } public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public int getport() { return port; } public void setport(int port) { this.port = port; } public channelsftp getsftp() { return sftp; } public void setsftp(channelsftp sftp) { this.sftp = sftp; } /**测试*/ public static void main(string[] args) { sftputils sftp = null; // 本地存放地址 string localpath = "d:/tomcat5/webapps/assess/documentsdir/documenttempdir/txtdata/"; // sftp下载路径 string sftppath = "/home/assess/sftp/jiesuan_2/2014/"; list<string> filepathlist = new arraylist<string>(); try { sftp = new sftputils("10.163.201.115", "tdcp", "tdcp"); sftp.connect(); // 下载 sftp.batchdownloadfile(sftppath, localpath, "assess", ".txt", true); } catch (exception e) { e.printstacktrace(); } finally { sftp.disconnect(); } } }
5.需要的时间辅助类,顺带记下,下次可以直接拿来用
/** * 时间处理工具类(简单的) * @author aaron * @date 2014-6-17 * @time 下午1:39:44 * @version 1.0 */ public class dateutil { /** * 默认时间字符串的格式 */ public static final string default_format_str = "yyyymmddhhmmss"; public static final string date_format_str = "yyyymmdd"; /** * 获取系统时间的昨天 * @return */ public static string getsystime(){ calendar ca = calendar.getinstance(); ca.set(calendar.date, ca.get(calendar.date)-1); date d = ca.gettime(); simpledateformat sdf = new simpledateformat("yyyymmdd"); string a = sdf.format(d); return a; } /** * 获取当前时间 * @param date * @return */ public static string getcurrentdate(string formatstr) { if (null == formatstr) { formatstr=default_format_str; } return date2string(new date(), formatstr); } /** * 返回年月日 * @return yyyymmdd */ public static string gettodaychar8(string dateformat){ return dateformatutils.format(new date(), dateformat); } /** * 将date日期转换为string * @param date * @param formatstr * @return */ public static string date2string(date date, string formatstr) { if (null == date || null == formatstr) { return ""; } simpledateformat df = new simpledateformat(formatstr); return df.format(date); } }
以上就是详解java sftp文件上传,下载及批量下载的实例代码的详细内容。
其它类似信息

推荐信息