Java operation SFTP and FTP
Import java. util. properties; import org. slf4j. logger; import org. slf4j. loggerFactory; import com. jcraft. jsch. channel; import com. jcraft. jsch. channelSftp; import com. jcraft. jsch. JSch; import com. jcraft. jsch. session;/*** @ description SFTP tool * @ author Luxh */public class SFTPUtils {private static final Logger Log = LoggerFactory. getLogger (SFTPUtils. class);/** FTP protocol */private static final String FTP_PROTOC OL = "sftp "; /*** get session * @ param host * @ param port * @ param username * @ param password * @ return */public static Session getSession (String host, int port, string username, String password) {Session session = null; try {Log.info ("init Session... "); JSch jsch = new JSch (); session = jsch. getSession (username, host, port); session. setPassword (password); Properties config = new Properties (); c Onfig. put ("StrictHostKeyChecking", "no"); session. setConfig (config); session. connect (); Log.info ("init session successful");} catch (Exception e) {Log. error ("init session failed");} return session;}/*** get ChannelSftp * @ param session * @ return */public static ChannelSftp 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");} return sftp ;} /*** upload * @ param src Source file path * @ param dst destination file path * @ param sftp */public static void upload (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 * @ param src the file to be downloaded * @ param dst storage path * @ param sftp */public static void download (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); Lo G.info ("download successful");} catch (Exception e) {Log. error ("download failed") ;}}/*** delete * @ param path the path of the file to be deleted * @ param sftp */public static void delete (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 the connection * @ param session *@ Param sftp */public static void close (Session session, ChannelSftp sftp) {if (sftp! = Null) {sftp. disconnect (); Log.info ("ChannelSftp disconnect");} if (session! = Null) {session. disconnect (); Log.info ("Session disconnect ");}}}
Using jsch Library: http://www.jcraft.com/jsch/