File server with freesshd, file server configuration will not elaborate.
Directly on the code, the code can be used directly.
Importcom.jcraft.jsch.*;ImportJava.io.InputStream;Importjava.util.Properties;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;/** * @authorFC *@versionV1.0 * @Title sftpconnect * @Package Com.jsch * @Descript: TODO () * @date: 2018/8/30 pm 3:50*/ Public classSftpconnect {PrivateString User; PrivateString password; PrivateString host; Private intPort; Privatechannelsftp channelsftp; PrivateSession session; PrivateLogger Logger = Loggerfactory.getlogger (sftpconnect.class); Private FinalString no_such_file = "NO SUCH FILE"; PublicSftpconnect (string user, string password, string host,intPort) { This. user =user; This. Password =password; This. Host =host; This. Port =Port; } Privatechannelsftp Connect () {Jsch Jsch=NewJsch (); Try{Session=jsch.getsession (User,host,port); Properties Sshconfig=NewProperties (); Sshconfig.put ("Stricthostkeychecking", "no"); Session.setpassword (password); Session.setconfig (Sshconfig); Session.connect (); Channelsftp= (channelsftp) session.openchannel ("Sftp"); Channelsftp.connect (); } Catch(jschexception e) {return NULL; } returnchannelsftp; } /*** Disconnect Connection*/ Private voidDisconnect () {channelsftp.disconnect (); Session.disconnect (); } Public Booleanuploadfile (String path,string filename, InputStream is) {if(Channelsftp = =NULL) {Logger.debug ("Initialize SFTP connection: Connection address: {}", host); Connect (); Logger.trace ("SFTP Connection initialization complete: {}", host); } Try{ValidatePath (path); Channelsftp.put (Is,filename); Disconnect (); } Catch(sftpexception e) {logger.error ("File upload failed: \n{}", E); return false; } return true; } /*** Verify server folder path, create new * if not present@paramPath*/ Private voidValidatePath (String Path)throwssftpexception {Try{channelsftp.lstat (path); CHANNELSFTP.CD (path); } Catch(sftpexception e) {if(No_such_file.equals (E.getmessage ())) {Logger.debug ("{} does not exist, create this path", path); String[] Paths= Path.split ("/"); for(String p:paths) {Try{channelsftp.cd (P); } Catch(sftpexception E1) {Channelsftp.mkdir (P); CHANNELSFTP.CD (P); } } }Else { Throwe; } } } /*** Download File *@paramPath *@paramfilename *@param: Is *@return */ PublicInputStream downfile (String path,string filename) {if(Channelsftp = =NULL) {Logger.debug ("Initialize SFTP connection: Connection address: {}", host); Connect (); Logger.trace ("SFTP Connection initialization complete: {}", host); } Try{channelsftp.cd (path); InputStream is=channelsftp.get (filename); Disconnect (); returnis ; } Catch(sftpexception e) {return NULL; } }}
Jsch implementing file Upload and download to SFTP server