JAVA in the use of ftpclient upload download __java

Source: Internet
Author: User
Tags ftp login server port

In the Java program, often need to deal with FTP, such as uploading files to the FTP server, download files, this article briefly describes how to use the FtpClient in the Jakarta Commons (in the Commons-net package) to achieve upload download files.

first, upload files

         principle is not introduced, we look directly at the Code view plain copy to clipboard print? /**    * Description:  uploading files to FTP server    *  @Version1.0 jul 27, 2008  4:31:09 PM by  Tri Hongbao (cuihongbao@d-heaven.com) Create    *  @param  url  FTP server hostname    *  @param  port ftp server port    *  @param  username  FTP login account    *  @param  password ftp login password    *  @param  path ftp Server Save Directory    *  @param  filename  uploaded to ftp server filename    *  @param  input  input stream    *  @return   Successfully returns TRUE, otherwise returns false    */   public static boolean  UploadFile (string url,int port,string username, string password, string  Path, string filename, inputstream input)  {        boolean success = false;        ftpclient ftp = new ftpclient ();        try {           int  reply;            ftp.connect (Url, port);//Connect FTP server            //If you use the default port, you can connect to the FTP server directly using Ftp.connect (URL)             ftp.login (username, password)/login             reply = ftp.getreplycode ();            if  (! Ftpreply.ispositivecompletion (Reply))  {                ftp.disconnect ();                return success;            }             Ftp.changeworkingdirectory (path);            ftp.storefile (filename, input);                                   input.close ();            ftp.logout ();            success = true;        } catch  (ioexception e)  {            e.printstacktrace ();        } finally {            if  (ftp.isconnected ())  {                try {                    Ftp.disconnect ();                } catch  ( Ioexception ioe)  {               &NBSP}            }        }        return success;   }<pre></pre>  

	/** * Description: Uploading files to FTP server * @Version1.0, 2008 4:31:09 PM by Tri Hongbao (cuihongbao@d-heaven.com) create * @param URL FTP Server hostname * @param port FTP server ports * @param username FTP login account * @param password FTP login password * @param path FTP server Save eye Record * @param filename uploaded to the FTP server * @param input stream * @return successfully returns TRUE, otherwise returns false */public static Boolean Uploa Dfile (String Url,int port,string Username, string password, string path, string filename, InputStream input) {Boolean s
		Uccess = false;
		ftpclient ftp = new FtpClient ();
			try {int reply;
			Ftp.connect (URL, port);//Connect FTP server//If the default port is used, you can connect the FTP server directly using the Ftp.connect (URL) ftp.login (username, password);/Login
			Reply = Ftp.getreplycode (); if (!
				Ftpreply.ispositivecompletion (Reply)) {ftp.disconnect ();
			return success;
			} ftp.changeworkingdirectory (path);			
			
			Ftp.storefile (filename, input);
			Input.close ();
			Ftp.logout ();
		Success = true;
		catch (IOException e) {e.printstacktrace (); } Finally {if (ftp.isconnected ()) {try {ftp.disconnect ();
	catch (IOException IoE) {}} return success; }

Below we write two small examples:

1. Upload the local file to the FTP server, the code is as follows: View plain copy to clipboard print? @Test public void Testuploadfromdisk () {try {FileInputStream in=new fileinputstream (New File ("D:/test            . txt "));            Boolean flag = UploadFile ("127.0.0.1", "Test", "Test", "D:/ftp", "test.txt", in);        SYSTEM.OUT.PRINTLN (flag);        catch (FileNotFoundException e) {e.printstacktrace (); }}<pre></pre>

 @Test public void Testuploadfromdisk () {try {FileInputStream in=new fileinputstream (New File ("D:
			/test.txt "));
			Boolean flag = UploadFile ("127.0.0.1", "Test", "Test", "D:/ftp", "test.txt", in);
		SYSTEM.OUT.PRINTLN (flag);
		catch (FileNotFoundException e) {e.printstacktrace (); }
	}

2. Generate a file on the FTP server and write a string to the file view plain copy to clipboard print? @Test    public void  Testuploadfromstring () {       try {            inputstream input = new bytearrayinputstream ("Test ftp"). GetBytes ("Utf-8"));            boolean flag = uploadfile (" 127.0.0.1 ", 21, " test ", " test ", " D:/ftp ", " test.txt ",  input);            system.out.println (flag);        } catch  (unsupportedencodingexception e)  {           e.printstacktrace ();        }   }<pre></pre>  

	@Test public
	void Testuploadfromstring () {
		try {
			InputStream input = new Bytearrayinputstream ("Test ftp"). GetBytes ("Utf-8"));
			Boolean flag = UploadFile ("127.0.0.1", "Test", "Test", "D:/ftp", "test.txt", input);
			SYSTEM.OUT.PRINTLN (flag);
		} catch (Unsupportedencodingexception e) {
			e.printstacktrace ();
		}
	}


Second, download the file

       the code to download files from the FTP server is also simple, as follows: View plain copy to clipboard print? /**    * Description:  download files from FTP server    *  @Version1.0 jul 27, 2008  5:32:36 PM by  Tri Hongbao (cuihongbao@d-heaven.com) Create    *  @param  url  FTP server hostname    *  @param  port ftp server port    *  @param  username  FTP login account    *  @param  password ftp login password    *  @param  remotePath  Relative paths on FTP server    *  @param  fileName  file name to download    *  @param  localPath  Save after download to local path    *  @return    */   public static boolean downfile ( string url, int port,string username, string password, string  Remotepath,string filename,string localpath)  {       boolean  Success =&nbSp;false;        ftpclient ftp = new ftpclient ();        try {           int  reply;            ftp.connect (Url, port);            //If you use the default port, you can connect to the FTP server directly using the Ftp.connect (URL)             ftp.login (Username, password);//Login            reply = ftp.getreplycode ();            if  (! Ftpreply.ispositivecompletion (Reply))  {                ftp.disconnect ();                return success;            &nbsp}            ftp.changeworkingdirectory (RemotePath);// Transfer to FTP server directory            FTPFile[] fs =  Ftp.listfiles ();            for (ftpfile ff:fs) {                if (Ff.getname (). Equals (FileName)) {                   File  Localfile = new file (localpath+ "/" +ff.getname ());                                         Outputstream is = new fileoutputstream (localfile);                 &nbsP;    ftp.retrievefile (Ff.getname (),  is);                     Is.close ();                }       &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}                        ftp.logout ();            success = true;        } catch  (ioexception e)  {            e.printstacktrace ();        } finally {            if  (ftp.isconnected ())  {                try {   &NBSP;&NBSp;              ftp.disconnect ();                } catch  ( Ioexception ioe)  {               &NBSP}            }        }        return success;   }<pre></pre>  

Related Article

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.