Packagecom.learning.spboot.utils;Importcom.jcraft.jsch.*;Importorg.apache.commons.net.ftp.FTPClient;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.InputStream;ImportJava.text.SimpleDateFormat;Importjava.util.Date;Importjava.util.Properties;ImportJava.util.Vector; Public classFtputils {//Remote server address Private Final StaticString homename = "47.104.99.125"; //FTP Port Private Final Static inthomeport = 22; Private Final StaticString userename = "* * *"; Private Final StaticString Password = "* * * * *"; Public Staticstring init (String dirpaht,string filepath) {channelsftp sftp=NULL; Channel Channel=NULL; Session sshsession=NULL; Jsch JSCJ=NewJsch (); Try{jscj.getsession (userename,homename,homeport); Sshsession=jscj.getsession (Userename,homename,homeport); Sshsession.setpassword (password); Properties Sshconfig=NewProperties (); Sshconfig.put ("Stricthostkeychecking", "no"); Sshsession.setconfig (Sshconfig); Sshsession.connect (); if(sshsession.isconnected ()) {System.out.println ("The connection was successful!"); System.out.println ("Session connected!"); /*sftp.setfilenameencoding ("UTF-8"); Sftp.*/Channel= Sshsession.openchannel ("SFTP"); Channel.connect (); SFTP=(CHANNELSFTP) channel; //determine if the current upload path exists Try{Vector<?> vector = Sftp.ls (dirpaht);//the first path does not exist and will error if(Vector = =NULL) { //Sftp.rmdir (dirpaht);Sftp.mkdir (DIRPAHT); } }Catch(Exception e) {e.getmessage (); Sftp.mkdir (DIRPAHT);//Create an upload path } //switch to directory upload directorysftp.cd (DIRPAHT); File File=NewFile (filepath); String filetype=file.getname (). substring (File.getname (). LastIndexOf (".") +1); String NewFileName=NewSimpleDateFormat ("YYYYMMDD"). Format (NewDate ()) + "." +filetype; InputStream ins=Newfileinputstream (file); //the Chinese nameSftp.put (INS,NewString (Newfilename.getbytes (), "UTF-8")); } Else{System.out.println ("Connection Failed!"); } } Catch(Exception e) {e.printstacktrace (); } return NULL; } Public Static voidMain (String []args) {NewFtputils (). Init ("/java/image/", "d:\\ development tools Software \\ideaImg\\011.jpg"); }}
Java FTP upload file tool class