Use ftpclient for upload and download in Java

Source: Internet
Author: User
Tags ftp login

In Java programs, you often need to deal with FTP, such as uploading and downloading files to the FTP server. This article briefly introduces how to use the ftpclient in Jakarta commons (in the Commons-Net Package) upload and download files.

1. upload files

The principle is not introduced. Let's look at the Code directly.

View plaincopy to clipboardprint?
  1. /**
  2. * Description: uploads files to the FTP server.
  3. * @ Version1.0 Jul 27,200 8 4:31:09 by Cui hongbao (cuihongbao@d-heaven.com) Creation
  4. * @ Param url ftp Server Hostname
  5. * @ Param port: FTP server port
  6. * @ Param username FTP Logon account
  7. * @ Param password FTP logon Password
  8. * @ Param path FTP server storage directory
  9. * @ Param filename the file name uploaded to the FTP server
  10. * @ Param input stream
  11. * @ Return returns true if the call succeeds. Otherwise, false is returned.
  12. */
  13. Public static Boolean uploadfile (string URL, int port, string username, string password, string path, string filename, inputstream input ){
  14. Boolean success = false;
  15. Ftpclient FTP = new ftpclient ();
  16. Try {
  17. Int reply;
  18. FTP. Connect (URL, Port); // connect to the FTP server
  19. // If the default port is used, you can use ftp. Connect (URL) to directly connect to the FTP server.
  20. FTP. login (username, password); // log on
  21. Reply = ftp. getreplycode ();
  22. If (! Ftpreply. ispositivecompletion (reply )){
  23. FTP. Disconnect ();
  24. Return success;
  25. }
  26. FTP. changeworkingdirectory (PATH );
  27. FTP. storefile (filename, input );
  28. Input. Close ();
  29. FTP. logout ();
  30. Success = true;
  31. } Catch (ioexception e ){
  32. E. printstacktrace ();
  33. } Finally {
  34. If (ftp. isconnected ()){
  35. Try {
  36. FTP. Disconnect ();
  37. } Catch (ioexception IOE ){
  38. }
  39. }
  40. }
  41. Return success;
  42. } <PRE> </PRE>
/*** Description: Upload File to FTP server * @ version1.0 Jul 27,200 8 4:31:09 by Cui 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 storage directory * @ Param the file name uploaded by filename to the FTP server * @ Param input stream * @ return returns true if return is successful, otherwise, 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 to the FTP server // if you use the default port, you can use ftp. connect (URL) directly to the FTP Server FTP. login (username, password); // log on to 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 ;}

 

Here are two small examples:

1. Upload the local file to the FTP server. The Code is as follows:

View plaincopy to clipboardprint?
  1. @ Test
  2. Public void testuploadfromdisk (){
  3. Try {
  4. Fileinputstream in = new fileinputstream (new file ("D:/test.txt "));
  5. Boolean flag = uploadfile ("127.0.0.1", 21, "test", "test", "d:/ftp", "test.txt", in );
  6. System. Out. println (FLAG );
  7. } Catch (filenotfoundexception e ){
  8. E. printstacktrace ();
  9. }
  10. } <PRE> </PRE>
@Testpublic void testUpLoadFromDisk(){try {FileInputStream in=new FileInputStream(new File("D:/test.txt"));boolean flag = uploadFile("127.0.0.1", 21, "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 plaincopy to clipboardprint?
  1. @ Test
  2. Public void testuploadfromstring (){
  3. Try {
  4. Inputstream input = new bytearrayinputstream ("test FTP". getbytes ("UTF-8 "));
  5. Boolean flag = uploadfile ("127.0.0.1", 21, "test", "test", "d:/ftp", "test.txt", input );
  6. System. Out. println (FLAG );
  7. } Catch (unsupportedencodingexception e ){
  8. E. printstacktrace ();
  9. }
  10. } <PRE> </PRE>
@Testpublic 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();}}

Ii. download files

The code for downloading files from an FTP server is also very simple. For more information, see:

View plaincopy to clipboardprint?
  1. /**
  2. * Description: downloads files from the FTP server.
  3. * @ Version1.0 Jul 27,200 8 5:32:36 by Cui hongbao (cuihongbao@d-heaven.com) Creation
  4. * @ Param url ftp Server Hostname
  5. * @ Param port: FTP server port
  6. * @ Param username FTP Logon account
  7. * @ Param password FTP logon Password
  8. * @ Param remotepath relative path on the FTP server
  9. * @ Param filename the name of the file to be downloaded
  10. * @ Param localpath: The local path saved after downloading
  11. * @ Return
  12. */
  13. Public static Boolean downfile (string URL, int port, string username, string password, string remotepath, string filename, string localpath ){
  14. Boolean success = false;
  15. Ftpclient FTP = new ftpclient ();
  16. Try {
  17. Int reply;
  18. FTP. Connect (URL, Port );
  19. // If the default port is used, you can use ftp. Connect (URL) to directly connect to the FTP server.
  20. FTP. login (username, password); // log on
  21. Reply = ftp. getreplycode ();
  22. If (! Ftpreply. ispositivecompletion (reply )){
  23. FTP. Disconnect ();
  24. Return success;
  25. }
  26. FTP. changeworkingdirectory (remotepath); // transfer to the FTP Server Directory
  27. Ftpfile [] FS = ftp. listfiles ();
  28. For (ftpfile FF: FS ){
  29. If (FF. getname (). Equals (filename )){
  30. File localfile = new file (localpath + "/" + ff. getname ());
  31. Outputstream is = new fileoutputstream (localfile );
  32. FTP. retrievefile (FF. getname (), is );
  33. Is. Close ();
  34. }
  35. }
  36. FTP. logout ();
  37. Success = true;
  38. } Catch (ioexception e ){
  39. E. printstacktrace ();
  40. } Finally {
  41. If (ftp. isconnected ()){
  42. Try {
  43. FTP. Disconnect ();
  44. } Catch (ioexception IOE ){
  45. }
  46. }
  47. }
  48. Return success;
  49. } <PRE> </PRE>

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.