JAVA SFTP文件上传、下载及批量下载实例
1.jsch官方API查看地址(附件为需要的jar)
http://www.jcraft.com/jsch/
2.jsch简介
JSch(JavaSecureChannel)是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。
SFTP(SecureFileTransferProtocol)安全文件传送协议。可以为传输文件提供一种安全的加密方法。SFTP为SSH的一部份,是一种传输文件到服务器的安全方式,但是传输效率比普通的FTP要低。
3.api常用的方法:
- put(): 文件上传
- get(): 文件下载
- cd(): 进入指定目录
- ls(): 得到指定目录下的文件列表
- rename(): 重命名指定文件或目录
- rm(): 删除指定文件
- mkdir(): 创建目录
- rmdir(): 删除目录
- put和get都有多个重载方法,自己看源代码
4.对常用方法的使用,封装成一个util类
importjava.io.File; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.util.ArrayList; importjava.util.Iterator; importjava.util.List; importjava.util.Properties; importjava.util.Vector; importorg.apache.log4j.Logger; importcom.jcraft.jsch.Channel; importcom.jcraft.jsch.ChannelSftp; importcom.jcraft.jsch.JSch; importcom.jcraft.jsch.Session; importcom.jcraft.jsch.SftpATTRS; importcom.jcraft.jsch.SftpException; importcom.jcraft.jsch.ChannelSftp.LsEntry; /** *sftp工具类 * *@authorxxx *@date2014-6-17 *@time下午1:39:44 *@version1.0 */ publicclassSFTPUtils { privatestaticLoggerlog=Logger.getLogger(SFTPUtils.class.getName()); privateStringhost;//服务器连接ip privateStringusername;//用户名 privateStringpassword;//密码 privateintport=22;//端口号 privateChannelSftpsftp=null; privateSessionsshSession=null; publicSFTPUtils(){} publicSFTPUtils(Stringhost,intport,Stringusername,Stringpassword) { this.host=host; this.username=username; this.password=password; this.port=port; } publicSFTPUtils(Stringhost,Stringusername,Stringpassword) { this.host=host; this.username=username; this.password=password; } /** *通过SFTP连接服务器 */ publicvoidconnect() { try { JSchjsch=newJSch(); jsch.getSession(username,host,port); sshSession=jsch.getSession(username,host,port); if(log.isInfoEnabled()) { log.info("Sessioncreated."); } sshSession.setPassword(password); PropertiessshConfig=newProperties(); sshConfig.put("StrictHostKeyChecking","no"); sshSession.setConfig(sshConfig); sshSession.connect(); if(log.isInfoEnabled()) { log.info("Sessionconnected."); } Channelchannel=sshSession.openChannel("sftp"); channel.connect(); if(log.isInfoEnabled()) { log.info("OpeningChannel."); } sftp=(ChannelSftp)channel; if(log.isInfoEnabled()) { log.info("Connectedto"+host+"."); } } catch(Exceptione) { e.printStackTrace(); } } /** *关闭连接 */ publicvoiddisconnect() { if(this.sftp!=null) { if(this.sftp.isConnected()) { this.sftp.disconnect(); if(log.isInfoEnabled()) { log.info("sftpisclosedalready"); } } } if(this.sshSession!=null) { if(this.sshSession.isConnected()) { this.sshSession.disconnect(); if(log.isInfoEnabled()) { log.info("sshSessionisclosedalready"); } } } } /** *批量下载文件 *@paramremotPath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/) *@paramlocalPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\) *@paramfileFormat:下载文件格式(以特定字符开头,为空不做检验) *@paramfileEndFormat:下载文件格式(文件格式) *@paramdel:下载后是否删除sftp文件 *@return */ publicListbatchDownLoadFile(StringremotePath,StringlocalPath, StringfileFormat,StringfileEndFormat,booleandel) { List filenames=newArrayList (); try { //connect(); Vectorv=listFiles(remotePath); //sftp.cd(remotePath); if(v.size()>0) { System.out.println("本次处理文件个数不为零,开始下载...fileSize="+v.size()); Iteratorit=v.iterator(); while(it.hasNext()) { LsEntryentry=(LsEntry)it.next(); Stringfilename=entry.getFilename(); SftpATTRSattrs=entry.getAttrs(); if(!attrs.isDir()) { booleanflag=false; StringlocalFileName=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); } } } } elseif(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); } } } } elseif(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("downloadfileissuccess:remotePath="+remotePath +"andlocalPath="+localPath+",filesizeis" +v.size()); } } catch(SftpExceptione) { e.printStackTrace(); } finally { //this.disconnect(); } returnfilenames; } /** *下载单个文件 *@paramremotPath:远程下载目录(以路径符号结束) *@paramremoteFileName:下载文件名 *@paramlocalPath:本地保存目录(以路径符号结束) *@paramlocalFileName:保存文件名 *@return */ publicbooleandownloadFile(StringremotePath,StringremoteFileName,StringlocalPath,StringlocalFileName) { FileOutputStreamfieloutput=null; try { //sftp.cd(remotePath); Filefile=newFile(localPath+localFileName); //mkdirs(localPath+localFileName); fieloutput=newFileOutputStream(file); sftp.get(remotePath+remoteFileName,fieloutput); if(log.isInfoEnabled()) { log.info("===DownloadFile:"+remoteFileName+"successfromsftp."); } returntrue; } catch(FileNotFoundExceptione) { e.printStackTrace(); } catch(SftpExceptione) { e.printStackTrace(); } finally { if(null!=fieloutput) { try { fieloutput.close(); } catch(IOExceptione) { e.printStackTrace(); } } } returnfalse; } /** *上传单个文件 *@paramremotePath:远程保存目录 *@paramremoteFileName:保存文件名 *@paramlocalPath:本地上传目录(以路径符号结束) *@paramlocalFileName:上传的文件名 *@return */ publicbooleanuploadFile(StringremotePath,StringremoteFileName,StringlocalPath,StringlocalFileName) { FileInputStreamin=null; try { createDir(remotePath); Filefile=newFile(localPath+localFileName); in=newFileInputStream(file); sftp.put(in,remoteFileName); returntrue; } catch(FileNotFoundExceptione) { e.printStackTrace(); } catch(SftpExceptione) { e.printStackTrace(); } finally { if(in!=null) { try { in.close(); } catch(IOExceptione) { e.printStackTrace(); } } } returnfalse; } /** *批量上传文件 *@paramremotePath:远程保存目录 *@paramlocalPath:本地上传目录(以路径符号结束) *@paramdel:上传后是否删除本地文件 *@return */ publicbooleanbacthUploadFile(StringremotePath,StringlocalPath, booleandel) { try { connect(); Filefile=newFile(localPath); File[]files=file.listFiles(); for(inti=0;i filePathList=newArrayList (); try { sftp=newSFTPUtils("10.163.201.115","tdcp","tdcp"); sftp.connect(); //下载 sftp.batchDownLoadFile(sftpPath,localPath,"ASSESS",".txt",true); } catch(Exceptione) { e.printStackTrace(); } finally { sftp.disconnect(); } } }
5.需要的时间辅助类,顺带记下,下次可以直接拿来用
/** *时间处理工具类(简单的) *@authorAaron *@date2014-6-17 *@time下午1:39:44 *@version1.0 */ publicclassDateUtil{ /** *默认时间字符串的格式 */ publicstaticfinalStringDEFAULT_FORMAT_STR="yyyyMMddHHmmss"; publicstaticfinalStringDATE_FORMAT_STR="yyyyMMdd"; /** *获取系统时间的昨天 *@return */ publicstaticStringgetSysTime(){ Calendarca=Calendar.getInstance(); ca.set(Calendar.DATE,ca.get(Calendar.DATE)-1); Dated=ca.getTime(); SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMdd"); Stringa=sdf.format(d); returna; } /** *获取当前时间 *@paramdate *@return */ publicstaticStringgetCurrentDate(StringformatStr) { if(null==formatStr) { formatStr=DEFAULT_FORMAT_STR; } returndate2String(newDate(),formatStr); } /** *返回年月日 *@returnyyyyMMdd */ publicstaticStringgetTodayChar8(StringdateFormat){ returnDateFormatUtils.format(newDate(),dateFormat); } /** *将Date日期转换为String *@paramdate *@paramformatStr *@return */ publicstaticStringdate2String(Datedate,StringformatStr) { if(null==date||null==formatStr) { return""; } SimpleDateFormatdf=newSimpleDateFormat(formatStr); returndf.format(date); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。