Java implementation of FTP file and folder upload and download 1

Source: Internet
Author: User
Tags ftp connection ftp file ftp login ftp server path getmessage file transfer protocol server port

Java implementation of FTP file and folder upload and download http://www.cnblogs.com/winorgohome/archive/2016/11/22/6088013.html

FTP is the abbreviation for file Transfer Protocol (document Transfer Protocol), and Chinese is called "Interfax protocol". Used for two-way transmission of control files on the Internet. At the same time, it is also an application (application). There are different FTP applications based on different operating systems, and all of these applications follow the same protocol to transfer files. In the use of FTP, users often encounter two concepts: "Download" (Download) and "Upload" (Upload). A "Download" file is a copy of a file from a remote host to its own computer; the "upload" file is a copy of the file from your computer to a remote host. In the Internet language, users can upload (download) files to (from) a remote host through a client program.

First downloaded the serv-u to set their own computer for the FTP file server, easy to operate. The following code is used in the FTP server has been created, and to write in the code of the FTP connection to the relevant data can be completed.

1.FTP file Upload and download (note is a single file upload and download)

Import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream;import Org.apache.commons.net.ftp.ftp;import Org.apache.commons.net.ftp.ftpclient;import Org.apache.commons.net.ftp.ftpfile;import org.apache.commons.net.ftp.ftpreply;/** * For FTP file upload and file download */public class    Ftpapche {private static ftpclient ftpclient = new FtpClient ();    private static String encoding = System.getproperty ("file.encoding"); /** * Description: Uploading files to FTP server * * @Version1.0 * @param URL * FTP server hostname * @param Port * FTP server PORTS * @param username * FTP login account * @param password * FTP login Password * @param path * FTP server to save the directory, if the root directory is "/" * @param filename * uploaded to the FTP server file name * @ param input * Local file input stream * @return return True, otherwise false */PubliC Static Boolean uploadfile (string url, int port, string username, string password, string path, String Filenam        E, InputStream Input) {Boolean result = false;            try {int reply;            If the default port is used, the FTP server Ftpclient.connect (URL) can be connected directly using Ftp.connect (URL);            Ftp.connect (URL, port);//Connect FTP server//Login ftpclient.login (username, password);            ftpclient.setcontrolencoding (encoding);            Verify that the connection is successful reply = Ftpclient.getreplycode (); if (!                Ftpreply.ispositivecompletion (Reply)) {System.out.println ("Connection failed");                Ftpclient.disconnect ();            return result;            }//Transfer working directory to the specified directory boolean change = ftpclient.changeworkingdirectory (path);            Ftpclient.setfiletype (Ftp.binary_file_type); if (change) {result = Ftpclient.storefile (new String (Filename.getbytes (encoding), "iso-8859-1"), input);               if (result) {System.out.println ("Upload succeeded!");            }} input.close ();        Ftpclient.logout ();        } catch (IOException e) {e.printstacktrace ();                } finally {if (ftpclient.isconnected ()) {try {ftpclient.disconnect ()};    } catch (IOException IoE) {}}} return result;  Upload local file to FTP server * */public void Testuploadfromdisk () {try {FileInputStream}/**            in = new FileInputStream (New File ("D:/test02/list.txt"));            Boolean flag = UploadFile ("10.0.0.102", +, "admin", "123456", "/", "Lis.txt", in);        SYSTEM.OUT.PRINTLN (flag);        } catch (FileNotFoundException e) {e.printstacktrace ();     }}/** * Description: Download files from FTP server * * @Version1.0 * @param URL * FTP server hostname   * @param Port *         FTP Server port * @param username * FTP login account * @param password * FTP login password * @par            AM RemotePath * Relative path on FTP server * @param filename * file name to download * @param localPath *            The path saved to local after download * @return */public static Boolean downfile (string url, int port, string username,        string password, string remotepath, String fileName, String LocalPath) {Boolean result = false;            try {int reply;                        ftpclient.setcontrolencoding (encoding);             */* In order to upload and download Chinese files, some places suggest using the following two sentences instead of * New String (remotepath.getbytes (encoding), "Iso-8859-1") transcoding.             * After testing, pass. *///ftpclientconfig conf = new Ftpclientconfig (FTPCLIENTCONFIG.SYST_NT);//Conf.setserverlanguageco            De ("zh");            Ftpclient.connect (URL, port); If you use the default port, you can connect directly to the FTP server ftpclient using Ftp.connect (URL).Login (username, password);//Login//Set the file Transfer type to binary Ftpclient.setfiletype (Ftpclient.binary_file_type);            Get the FTP login answer code reply = Ftpclient.getreplycode (); Verify if the login succeeds if (!                Ftpreply.ispositivecompletion (Reply)) {ftpclient.disconnect ();                SYSTEM.ERR.PRINTLN ("FTP server refused connection.");            return result; }//Transfer to the FTP server directory to the specified directory under Ftpclient.changeworkingdirectory (remotepath.getbytes (encoding), "I            So-8859-1 "));            Get file list ftpfile[] fs = Ftpclient.listfiles (); for (Ftpfile ff:fs) {if (Ff.getname (). Equals (FileName)) {file LocalFile = new File (l                    Ocalpath + "/" + ff.getname ());                    OutputStream is = new FileOutputStream (localfile);                    Ftpclient.retrievefile (Ff.getname (), is);                Is.close (); }} FTPCLIEnt.logout ();        result = true;        } catch (IOException e) {e.printstacktrace ();                } finally {if (ftpclient.isconnected ()) {try {ftpclient.disconnect ()};    } catch (IOException IoE) {}}} return result; /** * Download the file on the FTP server to local * */public void Testdownfile () {try {Boolean flag = Downfi            Le ("10.0.0.102", +, "admin", "123456", "/", "Ip.txt", "e:/");        SYSTEM.OUT.PRINTLN (flag);        } catch (Exception e) {e.printstacktrace ();        }} public static void Main (string[] args) {Ftpapche fa = new Ftpapche ();        Fa.testdownfile ();    Fa.testuploadfromdisk (); }}

2.FTP folder upload and download (note the entire folder)

Package Ftp;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import java.io.File;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.util.timezone;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.FTPReply;  Import Org.apache.log4j.Logger;    public class Ftptest_04 {private FtpClient ftpclient;    Private String strIp;    private int intport;    Private String user;      private String password;      private static Logger Logger = Logger.getlogger (FTPTest_04.class.getName ()); /* * FTP constructor */public Ftptest_04 (String strIp, Int. Intport, String user, String Password) {this.        StrIp = strIp;        This.intport = Intport;        This.user = user;        This.password = password;    This.ftpclient = new FtpClient ();      }    /*** @return Determine if login succeeded * */public Boolean FTPLogin () {Boolean islogin = false;        Ftpclientconfig ftpclientconfig = new Ftpclientconfig ();        Ftpclientconfig.setservertimezoneid (Timezone.getdefault (). GetID ());        This.ftpClient.setControlEncoding ("GBK");        This.ftpClient.configure (Ftpclientconfig);            try {if (This.intport > 0) {this.ftpClient.connect (This.strip, This.intport);            }else {this.ftpClient.connect (This.strip);            }//FTP server connection answer int reply = This.ftpClient.getReplyCode (); if (!                Ftpreply.ispositivecompletion (Reply)) {this.ftpClient.disconnect (); Logger.error ("Login FTP service failed!                ");            return islogin;            } this.ftpClient.login (This.user, This.password);            Set the transport Protocol This.ftpClient.enterLocalPassiveMode ();  This.ftpClient.setFileType (Ftpclient.binary_file_type);          Logger.info ("Congratulations" + This.user + "Successful login to FTP server");        IsLogin = true;            }catch (Exception e) {e.printstacktrace (); Logger.error (this.user + "Login FTP Service failed!        "+ e.getmessage ());        } this.ftpClient.setBufferSize (1024 * 2);        This.ftpClient.setDataTimeout (30 * 1000);    return islogin; }/** * @ Exit Close Server link * */public void Ftplogout () {if (null! = This.ftpclient && this.ft                  Pclient.isconnected ()) {try {Boolean reuslt = This.ftpClient.logout ();//Exit FTP server                if (reuslt) {Logger.info ("successfully exited server");                }}catch (IOException e) {e.printstacktrace (); Logger.warn ("Exit FTP server Exception!            "+ e.getmessage ()); }finally {try {this.ftpClient.disconnect ();//Close the FTP server connection}catch (IOE               Xception e) {e.printstacktrace ();     Logger.warn ("Close the FTP server connection exception!")                ");  }}}}/*** * Upload ftp file * @param localfile Local file * @param romotuploadepath upload Server path- should be/end * */public Boolean uploadfile (File localfile, String romotuploadepath) {Bufferedinputstream InS        Tream = null;        Boolean success = false; try {this.ftpClient.changeWorkingDirectory (Romotuploadepath);//change work path instream = new BUFFEREDINP            Utstream (New FileInputStream (LocalFile));            Logger.info (Localfile.getname () + "start uploading ...");            Success = This.ftpClient.storeFile (Localfile.getname (), instream);                if (success = = True) {Logger.info (Localfile.getname () + "upload succeeded");            return success;            }}catch (FileNotFoundException e) {e.printstacktrace ();        Logger.error (LocalFile + "not Found");        }catch (IOException e) {e.printstacktrace (); }finally {if (Instream = null) {try {instream.close ();                }catch (IOException e) {e.printstacktrace ();    }}} return success; /*** * Download File * @param remotefilename file name to download * @param localdires downloaded to the local path * @param remotedow              Nloadpath remotefilename Path * */public Boolean downloadFile (String remotefilename, String localdires,        String remotedownloadpath) {String strFilePath = Localdires + remotefilename;        Bufferedoutputstream outstream = null;        Boolean success = false;            try {this.ftpClient.changeWorkingDirectory (Remotedownloadpath);            OutStream = new Bufferedoutputstream (new FileOutputStream (strFilePath));            Logger.info (remotefilename + "Start download ....");            Success = This.ftpClient.retrieveFile (Remotefilename, OutStream);         if (success = = True) {       Logger.info (Remotefilename + "successfully downloaded to" + strFilePath);            return success;            }}catch (Exception e) {e.printstacktrace ();        Logger.error (remotefilename + "Download Failed");                    }finally {if (null! = OutStream) {try {outstream.flush ()};                Outstream.close ();                }catch (IOException e) {e.printstacktrace ();        }}} if (success = = False) {Logger.error (remotefilename + "Download failed!!!");    } return success;            }/*** * @ Upload folder * @param localdirectory * Local Folder * @param Remotedirectorypath * FTP Server path to directory "/" End * * * * Public boolean uploaddirectory (String localdirectory, String Remot        Edirectorypath) {file src = new File (localdirectory); try {remotedirectorypath = Remotedirectorypath + src.getname () + "/";           Boolean makedirflag = This.ftpClient.makeDirectory (Remotedirectorypath);            System.out.println ("localdirectory:" + localdirectory);            System.out.println ("Remotedirectorypath:" + Remotedirectorypath);            System.out.println ("Src.getname ():" + src.getname ());            System.out.println ("Remotedirectorypath:" + Remotedirectorypath);            System.out.println ("Makedirflag:" + makedirflag);        Ftpclient.listdirectories ();            }catch (IOException e) {e.printstacktrace ();        Logger.info (Remotedirectorypath + "Directory creation failed");        } file[] Allfile = Src.listfiles (); for (int currentfile = 0;currentfile < allfile.length;currentfile++) {if (!allfile[currentfile].isdirectory                ()) {String SrcName = Allfile[currentfile].getpath (). toString ();            UploadFile (New File (SrcName), Remotedirectorypath); }} for (int currentfile = 0;currentfile <                  allfile.length;currentfile++) {if (Allfile[currentfile].isdirectory ()) {//recursive            Uploaddirectory (Allfile[currentfile].getpath (). toString (), Remotedirectorypath);    }} return true; }/*** * @ download folder * @param localdirectorypath Local address * @param remotedirectory Remote Folder * * */public B  Oolean downloaddirectory (String localdirectorypath,string remotedirectory) {try {string fileName = new            File (remotedirectory). GetName ();            Localdirectorypath = Localdirectorypath + fileName + "//";            New File (Localdirectorypath). Mkdirs ();            ftpfile[] Allfile = This.ftpClient.listFiles (remotedirectory); for (int currentfile = 0;currentfile < allfile.length;currentfile++) {if (!allfile[currentfile].isdirec         Tory ()) {DownloadFile (Allfile[currentfile].getname (), Localdirectorypath, remotedirectory);       }} for (int currentfile = 0;currentfile < allfile.length;currentfile++) { if (Allfile[currentfile].isdirectory ()) {String Strremotedirectorypath = remotedirectory + "/" + Allfil                    E[currentfile].getname ();                Downloaddirectory (Localdirectorypath,strremotedirectorypath);            }}}catch (IOException e) {e.printstacktrace ();            Logger.info ("Failed to download folder");        return false;    } return true;    }//FtpClient set and Get function public ftpclient getftpclient () {return ftpclient;    } public void Setftpclient (FtpClient ftpclient) {this.ftpclient = ftpclient; } public static void Main (string[] args) throws IOException {ftptest_04 ftp=new ftptest_04 ("10.0.0.102", 2        1, "admin", "123456");        Ftp.ftplogin ();        System.out.println ("1"); Upload folder Boolean uploadflag = Ftp.uploaddirectory ("d:\\test02", "/");        If it is admin/then all the files, if only/so is to pass the folder System.out.println ("Uploadflag:" + uploadflag);        Download folder ftp.downloaddirectory ("D:\\tm", "/");    Ftp.ftplogout (); }}

Java implementation of FTP file and folder upload and download 1

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.