Java implementation FTP upload download

Source: Internet
Author: User
Tags create directory download file from ftp server ftp connection ftp upload file

The code is as follows

<span style= "FONT-SIZE:18PX;" >import Java.io.BufferedOutputStream; Import Java.io.File; Import Java.io.FileInputStream; Import Java.io.FileOutputStream; Import Java.io.FileWriter; Import java.io.IOException; Import Java.io.InputStream; Import Java.util.Arrays; Import java.util.List; Import org.apache.commons.net.ftp.FTPClient; Import Org.apache.commons.net.ftp.FTPClientConfig; Import Org.apache.commons.net.ftp.FTPFile; Import Org.apache.commons.net.ftp.FTPListParseEngine; Import org.apache.commons.net.ftp.FTPReply; Import org.dom4j.Document; Import Org.dom4j.DocumentHelper; Import org.dom4j.Element; Import Org.dom4j.io.OutputFormat; Import Org.dom4j.io.XMLWriter; public class Ftphelper {private ftpclient FTP = NULL;/** * FTP server */private String server;/** * User name */private STR ing uname; /** * Password * */private String password; /** * Connection port, default */private int port = 21; Private document document; Public Ftphelper (string server, int port, string uname, string password) {This. Server = server; if (This.port > 0) {this.port = port;} this.uname = uname; This.password = password; Initialize FTP = new ftpclient (); /** * Connect FTP Server * * @param server * @param uname * @param password * @return * @throws Exception */Public FTPCL Ient Connectftpserver () throws Exception {try {ftp.configure (Getftpclientconfig ()); Ftp.connect (This.server, This.port); if (!ftp.login (This.uname, This.password)) {ftp.logout (); ftp = NULL; return FTP;}//file type, default is ASCII Ftp.setfiletype (FTPC Lient. Binary_file_type); Ftp.setcontrolencoding ("GBK"); Set the passive mode Ftp.enterlocalpassivemode (); Ftp.setconnecttimeout (2000); Ftp.setbuffersize (1024); Response information int replycode = Ftp.getreplycode (); if ((! Ftpreply.ispositivecompletion (Replycode)) {//Close FTP connection closeftpclient ();//free space FTP = NULL; throw new Exception ("Login FTP Service The device fails, please check! [Server: "+ server +", "+" User: "+ uname +", "+" Password: "+ Password);} else {return FTP;}} catch (Exception e) {ftp.disconnect (); ftp = null; throw e;}}/** * Configure FTP connection Parameters * * @return * @throws Exception */public Ftpclientconfig Getftpclientconfig () throws Exception {St Ring Systemkey = ftpclientconfig.syst_nt; String Serverlanguagecode = "zh"; Ftpclientconfig conf = new Ftpclientconfig (Systemkey); Conf.setserverlanguagecode (Serverlanguagecode); Conf.setdefaultdateformatstr ("Yyyy-mm-dd"); return conf; /** * Upload files to the FTP root directory * * @param localfile * @param newName * New file name * @throws Exception */Public Boolean UploadFile (String localfile, String newName) throws Exception {InputStream input = null; Boolean success = false; try {F ile file = null; if (Checkfileexist (LocalFile)) {file = new file (localfile);} input = new FileInputStream (file); Success = Ftp.storefile (newName, input); if (!success) {throw new Exception ("File upload failed!");}} catch (Exception e) {throw e;} finally {if (input! = null) {Input.close ();}} return success; /** * Upload file to FTP root * * @param input * @param newName * New file name * @throws ExCeption */Public Boolean uploadfile (inputstream input, String newName) throws Exception {Boolean success = false; try { Success = Ftp.storefile (newName, input); if (!success) {throw new Exception ("File upload failed!");}} catch (Exception e) {throw e;} finally {if (input! = null) {Input.close ();}} return success; }/** * Specify path to FTP upload file * * @param localfile * @param newName * New file name * @param remotefoldpath * @throws EXC Eption */Public Boolean UploadFile (string localfile, String newName, String remotefoldpath) throws Exception {Inputstre AM input = null; Boolean success = false; try {File File = null, if (Checkfileexist (LocalFile)) {file = new file (localfile);} input = new FileInputStream (file); Change the current path to the specified path if (!this.changedirectory (Remotefoldpath)) {System.out.println ("Server path does not exist!"); return false;} success = FTP . StoreFile (newName, input); if (!success) {throw new Exception ("File upload failed!");}} catch (Exception e) {throw e;} finally {if (input! = null) {Input.close (); }} return success; }/** * Specify path to FTP upload file * * @param input * @param newName * New file name * @param remotefoldpath * @throws Excepti On */Public Boolean uploadfile (InputStream input, String newName, String remotefoldpath) throws Exception {Boolean succ ESS = false;  try {//Change the current path to the specified path if (!this.changedirectory (Remotefoldpath)) {System.out.println ("Server path does not exist!"); return false;} success = Ftp.storefile (newName, input); if (!success) {throw new Exception ("File upload failed!");}} catch (Exception e) {throw e;} finally {if (input! = null) {Input.close ();}} return success;  /** * Download file from FTP server * * @param remotepath * FTP path (without file name) * @param filename * Download filename * @param  LocalPath * Local Path */public Boolean DownloadFile (string RemotePath, String fileName, String localPath) throws Exception {Bufferedoutputstream output = null; Boolean success = false; try {//Check local path this.checkfileexist (LocalPath); Change the working Path if (!this.changedirectory (RemotePath)) {System.out.println ("Server path does not exist"); return false;}//Lists the list of files under the current working path list<ftpfile> fileList = This.getfilelist (); if (fileList = = NULL | | filelist.size () = = 0) {System.out.println ("The file does not exist under the current path of the server! "); return success; } for (Ftpfile ftpfile:filelist) {if (Ftpfile.getname (). Equals (FileName)) {File Localfilepath = new File (LocalPath + F Ile.separator + ftpfile.getname ()); Output = new Bufferedoutputstream (new FileOutputStream (Localfilepath)); Success = Ftp.retrievefile (Ftpfile.getname (), output); }} if (!success) {throw new Exception ("File download failed!");}} catch (Exception e) {throw e;} finally {if (output! = null) {Output.close ();}} return success; /** * Get file Stream from FTP server * * @param remotefilepath * @return * @throws Exception */Public InputStream downloadFile (Str ing Remotefilepath) throws Exception {return Ftp.retrievefilestream (Remotefilepath);}/** * Get a list of files under the specified path on the FTP server * @param filePath * @return */public list<ftpfile> getftpserverfilelist (String RemotEpath) throws Exception {Ftplistparseengine engine = ftp.initiatelistparsing (RemotePath); list<ftpfile> ftpfiles = Arrays.aslist (Engine.getnext (25)); return ftpfiles; /** * Gets the list of files under [specified path] on the FTP server * * @param path * @return * @throws Exception */public list<ftpfile> Getfileli St (String RemotePath) throws Exception {list<ftpfile> ftpfiles = arrays.aslist (Ftp.listfiles (RemotePath)); return ftpfiles; /** * Get the file list under FTP server [current working path] * * @param path * @return * @throws Exception */public list<ftpfile> Getfilel IST () throws Exception {list<ftpfile> ftpfiles = arrays.aslist (Ftp.listfiles ()); return ftpfiles;}/** * Change FTP server Work Path * * @param remotefoldpath */Public Boolean changedirectory (String remotefoldpath) throws Exception {return FTP . Changeworkingdirectory (Remotefoldpath); }/** * Delete file * * @param remotefilepath * @return * @throws Exception */Public Boolean deleteftpserverfile (String R Emotefilepath) throws Exception {return FTP. DeleteFile (Remotefilepath); }/** * Create directory * * @param remotefoldpath * @return * */public Boolean createfold (String remotefoldpath) throws Exceptio  n {Boolean flag = Ftp.makedirectory (Remotefoldpath), if (!flag) {throw new Exception ("Failed to create Directory");} return false;}/** *  Delete directory * @param remotefoldpath * @return * @throws Exception */public boolean deletefold (String Remotefoldpath) throws Exception {return ftp.removedirectory (Remotefoldpath);}/** * Delete directories and files * * @param remotefoldpath * @return */PU Blic boolean deletefoldandsubfiles (String remotefoldpath) throws Exception {Boolean success = false; list<ftpfile> list = This.getfilelist (Remotefoldpath); if (list = = NULL | | list.size () = = 0) {return deletefold (Remotefoldpath);} for (Ftpfile ftpfile:list) {String name = Ftpfile.getname (); if (Ftpfile.isdirectory ()) {success = Deletefoldandsubfiles (Remotefoldpath + "/" + name); if (!success) break;} else {s uccess = Deleteftpserverfile (Remotefoldpath + "/" + name); if (!success) break; }} if (!success) return false; Success = Deletefold (Remotefoldpath); return success; /** * Check if local path exists * * @param filePath * @return * @throws Exception */public boolean checkfileexist (String Filepa Th) throws Exception {Boolean flag = false; File File = new file (FilePath); if (!file.exists ()) {throw new Exception ("The local path does not exist, please check!");} else {flag = true;} return flag; }/** * Create XML file * @return */public Element getcurrentelement () {document = Documenthelper.createdocument (); return doc Ument.addelement ("root"); /** * Generate directory XML file */public void Createdirectoryxml (String remotepath,element fatherelement) throws exception{list<f tpfile> list = This.getfilelist (); for (Ftpfile ftpfile:list) {Element currentelement = fatherelement;//current directory node String newremotepath = remotepath+ Ftpfile.getname (); if (Ftpfile.isdirectory ()) {Element direlement = fatherelement.addelement ("dir"); Direlement.addattribute ("Name", Ftpfile.getname ()); Currentelement = Direlement This.changedirectory (Newremotepath); Start Createdirectoryxml (newremotepath,direlement) from the root directory; }else{Element fileelement = fatherelement.addelement ("file");//File Node Fileelement.settext (Ftpfile.getname ());}}         }/** * Save XML */public void SaveXML () {XMLWriter output = new XMLWriter ();         Output formatted OutputFormat format = Outputformat.createprettyprint ();             try {output = new XMLWriter (New FileWriter ("Src/com/shine/ftp/config/dir.xml"), format);             Output.write (this.document);         Output.close ();         } catch (IOException e) {e.printstacktrace ();  }}/** * Close FTP connection * * @param FTP * @throws Exception */public void Closeftpclient (ftpclient ftp) throws Exception {  try {if (ftp.isconnected ()) ftp.logout (); Ftp.disconnect ();} catch (Exception e) {throw new Exception ("Error closing FTP service!");} /** * Close FTP connection * * @throws Exception */public void closeftpclient () throws Exception {this.closeftpclient (this.ft p); } /** * Get Attribute Method * */Public ftpclient getftp () {return FTP,} public String Getserver () {return server;} pub Lic string Getuname () {return uname;} public String GetPassword () {return password,} public int getport () {return por T }/** * Set Attribute Method * */public void Setftp (ftpclient ftp) {this.ftp = FTP;} public void Setserver (String s  erver) {this.server = server;} public void Setuname (string uname) {this.uname = uname;} public void SetPassword (string Password) {this.password = password;} public void Setport (int port) {this.port = port;}/** * Main method (TEST) * * Problem: Upload life  The new file name cannot have Chinese, otherwise the upload fails. * * @param args */public static void main (string[] args) {try {ftphelper fu = new Ftphelper ("192.168.2.18", +, "adm Inistrator "," Sunshine "); Fu.connectftpserver (); Element fatherelement = Fu.getcurrentelement (); Fu.createdirectoryxml ("/", fatherelement); Fu.savexml (); } catch (Exception e) {System.out.println ("Exception information:" + e.getmessage ());}} }</span>


Note: Detailed information is in the Java tutorial Web

Java implementation FTP upload download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.