Importjava.util.Properties;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportCom.jcraft.jsch.Channel;Importcom.jcraft.jsch.ChannelSftp;ImportCom.jcraft.jsch.JSch;Importcom.jcraft.jsch.Session;/*** @description SFTP tool *@authorLuxh*/ Public classSftputils {Private Static FinalLogger Log = Loggerfactory.getlogger (sftputils.class); /**FTP Protocol*/ Private Static FinalString Ftp_protocol = "SFTP"; /*** Get session *@paramHost *@paramPort *@paramusername *@paramPassword *@return */ Public StaticSession getsession (String host,intport, string Username, string password) {Session Session=NULL; Try{log.info ("Init session ..."); Jsch Jsch=NewJsch (); Session=jsch.getsession (username, host, port); Session.setpassword (password); Properties Config=NewProperties (); Config.put ("Stricthostkeychecking", "no"); Session.setconfig (config); Session.connect (); Log.info ("Init session Successful"); }Catch(Exception e) {log.error ("Init session Failed"); } returnsession; } /*** Get CHANNELSFTP *@paramSession *@return */ Public StaticChannelsftp Getchannelsftp (Session session) {CHANNELSFTP sftp=NULL; Try{log.info ("Init channelsftp ..."); Channel Channel=Session.openchannel (Ftp_protocol); Channel.connect (); SFTP=(CHANNELSFTP) channel; Log.info ("Init channelsftp Successful"); }Catch(Exception e) {log.error ("Init channelsftp failed"); } returnsftp; } /*** Upload *@paramsrc source file path *@paramDST destination File path *@paramsftp*/ Public Static voidupload (string src, string dst, Channelsftp sftp) {Try{log.info ("Begin upload ..."); Log.info ("src File is:{}", SRC); Log.info ("DST file is:{}", DST); Sftp.put (SRC, DST); Log.info ("Upload Successful"); } Catch(Exception e) {log.error ("Upload Failed"); } } /*** Download *@paramsrc file to download *@paramDST Storage Path *@paramsftp*/ Public Static voidDownload (string src, string dst, Channelsftp sftp) {Try{log.info ("Begin download ..."); Log.info ("src File is:{}", SRC); Log.info ("DST file is:{}", DST); Sftp.get (SRC, DST); Log.info ("Download Successful"); } Catch(Exception e) {log.error ("Download Failed"); } } /*** Delete *@parampath of file to delete *@paramsftp*/ Public Static voidDelete (String path, channelsftp sftp) {Try{log.info ("Begin Delete ..."); Log.info ("DST file is: {}", path); SFTP.RM (path); Log.info ("Delete Successful"); } Catch(Exception e) {log.error ("Delete Failed"); } } /*** Close Connection *@paramSession *@paramsftp*/ Public Static voidClose (Session session, Channelsftp SFTP) {if(SFTP! =NULL) {sftp.disconnect (); Log.info ("Channelsftp Disconnect"); } if(Session! =NULL) {session.disconnect (); Log.info ("Session Disconnect"); } } }
Java Operation SFTP