Android FTP Case Study

Source: Internet
Author: User
Tags create directory ftp client

  1. How to use:
  2. FtpClient client = new ftpclient ();
  3. Client.connect ("ftp.host.com", 8021);
  4. Client.login ("Carlo", "MyPassword");
  5. No exception indicates a successful connection, otherwise the mat throws a Ftpexception exception.
  6. Of course, there are some overloaded methods, if the port is 21 can be used Client.connect (host);
  7. In order to handle anonymous login, you can Client.login ("Anonymous", "ftp4j"), the user name is anonymous, the password is arbitrary.
  8. After logging in, you need to operate the server, such as directory display, entry, etc.;
  9. String dir = client.currentdirectory (); Show current directory
  10. Modify the entered directory
  11. Client.changedirectory (NewPath);
  12. You can use a relative path, or you can use an absolute path, as in the following two types.
  13. Client.changedirectory ("/an/absolute/one");
  14. Client.changedirectory ("relative");
  15. If you only want to go to the previous layer: Client.changedirectoryup ();
  16. There are two special directories in the ftp4j.   ",".. ", respectively, representing the root directory and the previous level directory.
  17. Rename: Client.rename ("Oldname", "newname");
  18. or move files: Client.rename ("MyFile.txt", "Myfolder/myfile.txt");
  19. Delete file: Client.deletefile (Relativeorabsolutepath); You can use a relative or absolute path.
  20. Create directory: Client.createdirectory ("NewFolder");
  21. Delete directory: Client.deletedirectory (Absoluteorrelativepath);
  22. Show files, directories, links
  23. Because of the different server, the format of the returned file list is also different, possibly UNIX, or win. FTP4J Directory support:
  24. UNIX style and variants (i.e. MAC style)
  25. DOS style
  26. NetWare Styles
  27. Eplf
  28. MLSD
  29. . Displays the current catalog file: ftpfile[] list = Client.list ();
  30. Ftpfile contains the information you need, from type to whether it is a directory or a file, or a link.
  31. In addition to filtering:
  32. ftpfile[] List = Client.list ("*.jpg"); filter, show only pictures
  33. If you want to know how to modify the previous period, you need to get it separately, not from the list () method above:
  34. Java.util.Date MD = client.modifieddate ("filename.ext");
  35. The next step is to upload and download:
  36. Client.download ("remotefile.ext", new java.io.File ("Localfile.ext"));
  37. Client.upload (new java.io.File ("Localfile.ext"));
  38. Upload of additional content
  39. Client.append (new java.io.File ("Localfile.ext"));
  40. These are blocking methods that are returned only after completion, so a ftpclient can only be transferred at the same time. If you want multiple files to be transferred simultaneously, you can use multiple ftpclient,ftpclient to connect to the server separately.
  41. Today's software is not just functional implementation, but also pay attention to the user experience, so upload download need to know the progress, ftp4j through Ftpdatatransferlistener this interface to achieve, if there is a method:
  42. Public void transferred (int length) {
  43. Yet other length bytes have been transferred since the last time this
  44. This method is said to be in the distance from the last transmission to the content of this transmission,
  45. If you want to have a progress bar, need to know the total amount, and then the current amount of transmission, so need to do some processing, such as at the beginning of the upload, get the local file upload size, and then from this interface to get the transferred files superimposed to get the total number of files transferred, and then calculate progress.
  46. From ftpclient you can know: on upload: listener.transferred (l); L represents the amount of this transmission, but it doesn't seem to be what we want,
  47. Modified to: listener.transferred (done); This do represents the total amount of uploads, which is already there, and is good to use directly.
  48. }
  49. You can then add this listener client.download ("Remotefile.ext", new java.io.File ("Localfile.ext") by overloading the method, New   Mytransferlistener ());, others slightly.
  50. For the same ftpclient, operations between multiple threads are affected, such as the ability to invoke Abortcurrentdatatransfer () in other threads to knot the current transport behavior.
  51. This method passes false to indicate a sudden stop, and passing in true indicates that sending the Abor command is a legitimate end.   Then there will be ftpabortedexception abnormalities.
  52. FTP4J also supports breakpoints:
  53. Client.download ("Remotefile.ext", new java.io.File ("Localfile.ext"), 1056); expression starting from 1057   , the front does not need to transfer again.
  54. Uploads are similar.
  55. Active vs. Passive transmission:
  56. Active transport Behavior:
  57. The client sends the IP address and port number to the server
  58. Client requests the server to transfer data and start listening ports
  59. Server connection address and port
  60. The data transfer is initiated by a new channel.
  61. Proactive need for client support to receive information if the client has a firewall, proxy, etc., there will be some problems,
  62. Passive transfer behavior:
  63. The client requests the server to prepare for passive data transfer.
  64. The server replies with IP and port.
  65. The client request transmission is also connected.
  66. The data transfer is initiated by a new channel.
  67. Change in the following ways:
  68. Client.setpassive (false); //Active mode
  69. Client.setpassive (true); //Passive mode
  70. The default is passive.
  71. These properties can be set by System properties:
  72. such as Ftp4j.activeDataTransfer.acceptTimeout set timeout time:
  73. java-dftp4j.activedatatransfer.hostaddress=178.12. 34.167
  74. -dftp4j.activedatatransfer.portrange=6000-7000
  75. -dftp4j.activedatatransfer.accepttimeout=MyClass
  76. Set property values directly in the code. i.e.:
  77. System.setproperty ("ftp4j.activeDataTransfer.hostAddress", "178.12.34.167");
  78. System.setproperty ("Ftp4j.activeDataTransfer.portRange", "6000-7000");
  79. System.setproperty ("Ftp4j.activeDataTransfer.acceptTimeout", "5000");
  80. Binary and text transfer types:
  81. From the source can be seen after the prefix name to determine the type of file, so personally think, uploaded files need to know what type, accidentally changed the binary file to txt suffix, there may be some problems.
  82. Client.settype (ftpclient.type_textual);
  83. Client.settype (ftpclient.type_binary);
  84. Client.settype (Ftpclient.type_auto);
  85. Of course it provides some custom types of Client.settextualextensionrecognizer (Myrecognizer);
  86. Some servers support data compression transmission, called Mode Z. Can be passed client.setcompressionenabled (true); Open, before this can be confirmed:boolean compressionenabled =   Client.iscompressionenabled ();
  87. Site Specifications and commands:
  88. ftpreply reply = Client.sendsitecommand ("YOUR COMMAND");
  89. You can also customize the command
  90. ftpreply reply = Client.sendcustomcommand ("YOUR COMMAND");
  91. Returns a Ftpreply object. You can get some return code, information, etc. from this object.
  92. -----------------------------------------------
  93. Above is some knowledge of ftp4j's documentation. With this knowledge, it is relatively easy to develop an Android client.
  94. If I want to get the file directory operation of the server (select file, select directory, enter directory)
  95. You can use Listview+listadapter to display directories and files, and then because of the Android operation you can use Onitemlongclicklistener long press and short press Onitemclicklistener to specify some actions separately, As a short press you can choose to enter the directory:
  96. Public void Onitemclick (adapterview<?> adapterview, view view, int i, long l) {
  97. Ftpfile Ftpfile=mfilelist.get (i);
  98. String Filename=ftpfile.getname ();
  99. if (".."). Equals (filename) {
  100. LOG.D (TAG, "Change directory up.");
  101. Changedirectoryup ();
  102. } Else if (".". Equals (filename) {
  103. LOG.D (TAG, "Change Directory root");
  104. Changedirectory ("/");
  105. } Else {
  106. If (Ftpfile.gettype () ==ftpfile.type_directory) {
  107. LOG.D (TAG, "Change directory:" +filename);
  108. Changedirectory (filename);
  109. }
  110. }
  111. }
  112. Mftpclient.changedirectory (path);
  113. Mftpclient.changedirectoryup (); Is the method that is ultimately called above.
  114. Then in the long press:
  115. Ftpfile Ftpfile=mfilelist.get (i);
  116. String Filename=ftpfile.getname ();
  117. if (".."). equals (filename) | | ".". Equals (filename) {
  118. LOG.D (TAG, "no treatment Here");
  119. } Else {
  120. If (Ftpfile.gettype () ==ftpfile.type_directory) {
  121. LOG.D (TAG, "Change directory:" +filename);
  122. Selectdirectory (filename);
  123. }
  124. }
  125. The Selectdirectory () method is to upload the destination as a selected directory. You can then pass in the local file to this directory.
  126. Called after changing the directory:
  127. Private  void refreshfiles (ftpclient mftpclient) throws IOException, Ftpillegalreplyexception, ftpexception {
  128. Ftpfile[] files=new ftpfile[0];
  129. try {
  130. Files=mftpclient.list ();
  131. List<ftpfile> ftpfiles= (list<ftpfile>) arrays.aslist (files);
  132. Mfilelist.clear ();
  133. Mfilelist.addall (Ftpfiles);
  134. Message Message=message.obtain (Mhandler, refresh_file);
  135. Message.obj=mftpclient.currentdirectory ();
  136. Mhandler.sendmessage (message);
  137. Here is the refresh ListView.
  138. } catch (Ftpdatatransferexception e) {
  139. E.printstacktrace ();
  140. } catch (Ftpabortedexception e) {
  141. E.printstacktrace ();
  142. } catch (Ftplistparseexception e) {
  143. E.printstacktrace ();
  144. }
  145. }
  146. With the ability to upload and download, you can use it, build a simple FTP server, Homeftpserver is a good thing, and then take photos or videos to upload. The other will not say, directly to the code. The completed program can be used, but somewhat rudimentary, for informational purposes only. The current demand is to take photos to video and upload to FTP.

ftpj4:http://www.sauronsoftware.it/projects/ftp4j/download.php:ftp4j 1.7.1 release, Java FTP client class Library

Ftp4j 1.7.1 Released, this version of Ftpconnector new Setusesuggestedaddressfordataconnections () method is used to determine whether to trust the server's address returned via the PASV command, fixed automatic noop Timer bug, call SimpleDateFormat to thread installation mode, improve the data transfer program to be compatible with more servers and proxy servers.

FTP4J is an FTP client Java class Library that implements most of the functionality that the FTP client should have. You can embed ftp4j into your Java application to transfer files (including uploads and downloads), browse directories and files on remote FTP servers, create, delete, rename, move remote directories and files. FTP4J provides a variety of ways to connect to remote FTP servers, including: direct connection via TCP/IP, connection via FTP proxy, HTTP proxy, socks4/4a proxy, and SOCKS5 proxy via SSL secure connection.

Ftp4j 1.7 was released, and the main improvements included:

    • Modifications to the FTP connector schema
    • Ftpconnector is no longer an interface, it becomes an abstract class, and some connections with timeout detection are implemented.
    • Callers can set time-outs for connection, read, and shutdown operations
    • Provide a method for interrupting the connection, ftpclient.abortcurrentconnectionattempt ();
    • Fixed bug in Httptunnelconnector

http://www.sauronsoftware.it/projects/ftp4j/download.php

http://blog.csdn.net/dahuaishu2010_/article/details/7640768

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.