Java Lightweight call FTP upload (Android available)

Source: Internet
Author: User

Today, HTTP breakpoint upload, WebSocket breakpoint upload rise, the FTP protocol has been replaced by the potential, but FTP as the name implies, is always for the file transfer service, the specific HTTP does not have the advantage: the first is suitable for large files, multi-batch upload, general 10MB or even on the file can also, and the progress bar, breakpoints, multi-threaded upload and other functions are readily available, the next development and maintenance is convenient---the server can use off-the-shelf solutions, such as the classic IIS FTP, SERVU, or write an FTP file receiver program to explain, but such a lot of wheels, such as recent concerns Nodejs also has the open Source FTP service scheme, so the service side recommends ready-made, and one point is that the server generally does not need coding but the relevant settings parameters can be, the client scenario, there are many options. Aside from the Java domain in a large number of open source FTP projects, in fact, Java class Library comes with an FTP client, but not as a standard library appears, and contained in the Rt.jar sun.net.* under; Finally, I think the advantage of FTP is that it comes with an account system, and even the ability to fine Score of

I started with the org.apache.commons.net.ftp.* package, but the relevant examples can not find the upload progress, and I heard that "with FtpClient (Apache) want to forcibly join the upload file speed detection is more troublesome." I was depressed, so I had to try other options. Discover the Java open source world is still wonderful, all kinds of FTP Client abound,


form the source of "Using Java to implement FTP bulk file upload download."

So much how to choose? If it is a simple upload download, not to introduce a bloated third-party library, using Sun-produced sun.net.ftp.FtpClient can be satisfied. After I have tried ftpclient, can join the ability to get progress, so you can discard more than 200 KB Apache FTP package. Unfortunately, on the Android project, it's not working well.

What do you say? The JDK self-built system for Android is not a package that joins a non-standard library such as Rt.jar (and the WEB environment is stress-free). I Baidu a bit, although can provide some ftpclient source code but not complete. Fortunately Java is open source,--moving to Google search immediately to search the full code of the JDK. At first it was CSDN downloaded, but the wonderful


Think of Java Boolean type can use 0/1 to indicate that is more than the old version of Ah, so then all kinds of error is unavoidable.

Then find a new version of the JDK,--OPENJDK 1.7, this can have, the latest source code, comments also have, but is evolved "too advanced", the package is too thin, dependent on N classes, pulled out too laborious. What to do? Back to the second, to a 1.6 see how, sure enough, 1.6 of the principle is just enough, mainly the following several categories.

Here is a description of the relevant API.

Sun.net.ftp.FtpClient This class library primarily provides classes for establishing FTP connections. Using these classes, programmers can telnet to an FTP server, enumerate directories on that server, set up transport protocols, and transfer files. The FtpClient class covers almost all FTP functions, and the FtpClient instance variable holds various information about establishing a "proxy".

public static Boolean Useftpproxy
This variable is used to indicate whether an agent is used in the FTP transfer process, so it is actually a token, which, if true, indicates that a proxy host was used.

public static String ftpproxyhost This variable is valid only if the variable useftpproxy is true, and is used to save the proxy host name.

public static int Ftpproxyport This variable is valid only if the variable useftpproxy is true to hold the port address of the agent host.

FtpClient has three different forms of constructors, as follows:

1, public ftpclient (String hostname,int Port) This constructor establishes an FTP connection using the given hostname and port number.

2. Public ftpclient (String hostname)
This constructor uses the given hostname to establish an FTP connection using the default port number.

3, FtpClient ()
This constructor creates a FtpClient class, but does not establish an FTP connection. At this point, the FTP connection can be established using the OpenServer method.

Once the class ftpclient is established, you can use this class method to open the connection to the FTP server. Class FtpClient provides the following two methods that can be used to open a connection to an FTP server.

public void OpenServer (String hostname)
This method is used to establish a connection to the FTP server on the specified host, using the default port number.

public void OpenServer (String host,int Port)
This method is used to establish a connection to the FTP server on the specified host and on the specified port.

After the connection is opened, the next task is to register to the FTP server. You need to use the following method.

public void Login (String username,string password)
This method uses the parameters username and password to log on to the FTP server. Users who have used Intemet should know that the anonymous FTP server's login user name is anonymous, and the password is usually in its own e-mail address.

Here are some of the control commands provided by the FtpClient class.

public void CD (String remotedirectory): This command is used to switch directories on the remote system to the directory specified by the parameter remotedirectory.
public void Cdup (): This command is used to switch directories on the remote system to the previous level directory.
Public String pwd (): This command displays the status of the directory on the remote system.
public void Binary (): This command sets the transfer format to binary format.
public void ASCII (): This command sets the transport protocol to ASCII format.
public void rename (String string,string string1): This command renames a directory or file on a remote system.

In addition to the methods described above, class FtpClient also provides several methods that can be used to pass and retrieve catalog manifests and files. These methods return the input and output streams that are available for reading or writing. Here are some of the main methods.

Public Telnetinputstream list ()
Returns the input stream corresponding to the current directory on the remote machine.

Public Telnetinputstream get (String filename)
Get the file filename on the remote machine and transfer the file locally with Telnetinputstream.

Public Telnetoutputstream put (String filename)
Writes an output stream, which transmits the file filename to the remote computer through this output stream.

So far, we have extracted the SUN.NET.FTP package separately, and Android can use it.

The following is an example of the invocation, mainly the Uploadftp tool class, inheriting ftpclient. Uploadprogresslistener is the upload progress bar controller, where you can modify the update () Notification UI updates progress bar.

Package Ftp;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import java.io.File;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream; Import Java.io.outputstream;import Sun.net.telnetinputstream;import Sun.net.telnetoutputstream;import Sun.net.ftp.ftpclient2;public class Uploadftp extends FtpClient2 {    public uploadftp (String server, int port) throws ioexception  {        super (server, port);    }     /**     * Upload local files to FTP server      *      * @param source&nbs p;    *            Local path to uploaded files      * @ param target     *            file path for uploading to FTP      * @return      */    public void upload (String souRCE, String target) {        telnetoutputstream ftp = null;         inputstream file = null;                try {& nbsp;           binary ();                        ftp = put (target);            file = new FileInputStream (source);             bufferedinputstream in = new Bufferedinputstream (file);                         new progresslistener (). Copy (in, new Bufferedoutputstream (FTP), in.available ());                        system.out.print ("Put file suc from" + Source +"   to " + target + "\ r \ n");        } catch (IOException e) {   &N bsp;        e.printstacktrace ();        } finally {             try {                if (FTP! = null) ftp.close ();                 if (file! = null) file.close ();            } catch ( IOException e) {                e.printstacktrace ();             }        }     }    /**     * Download required files from FTP      *      * @param source      *           Path and file name on FTP      * @param target     *             Local path to save      * @return      */    public void GetFile ( String source, String target) {        telnetinputstream ftp = null;    & nbsp;   outputstream file = null;                try {            binary ();             ftp = Get (source);            file = new FileOutputStream (new File);                         progresslistener listener = new Progresslistener ();             listener.setfilename (target);            listener.copy (                 New Bufferedinputstream (FTP),                 new Bufferedoutputstream (file),                 getfilesize (Source, FTP)             );                 system.out.print ("Get file suc from" + Source + "   to " + target + "\ r \ n ");        } catch (IOException e) {           & Nbsp;e.printstacktrace ();        } finally {             try {                if (FTP! = null) Ftp.close ();                if (file! = null) file.close ();            } catch ( IOException e) {                e.printstacktrace ();             }        }     }    /**     * To calculate the download speed and percentage, read the ftp file size      *      * @param s ource     * @param ftp     * @return      * @throws ioexception   &N Bsp */    private int GetFileSize (String source, Telnetinputstream ftp) throws IOException {   & nbsp;    //Here The combination use is must get sendserver after to readserverresponse         Sendserver ("SIZE" + source + "\ r \ n");                if ( Readserverresponse () = = 213) {            string msg = getresponsestring ();                        try {                 return Integer.parseint (msg.substring (3). Trim ());            } catch (Exception e) {}        }                 return 0;    }    public static void Main (string[] args) & nbsp {        uploadftp client;        try {            client = new Uploadftp ("192.168.61.83", +);             client.login ("Upup", "[email protected]");//            client. Putfile ("D:\\code.jar", "/test/1344439.jar");             client.upload ("E:\\aa.mp4", "/temp/zzz.mp4");            client.closeserver ();        } catch ( IOException e) {            e.printstacktrace ();         }    }}

Package Ftp;import Java.io.ioexception;import Java.io.inputstream;import java.io.outputstream;/** * upload Progress   * */public class Progresslistener {    private String filename;    private volatile Long bytesread;    private volatile long contentlength;    public void update (long Abytesread, long acontentlength) {        bytesread = abytesread/1024l;   & nbsp;    contentlength = acontentlength/1024l;        //Long megaBytes = abytesread/1048576l;        system.out.println ("Upload or download file:" + fileName + ", File size:" + Abytesread + "/" + acontentlength);    }    /**     *      * @ Param pin     * @param pout     * @return      * @throws Ioexception &nbs P   */    public long Copy (inputstReam in, outputstream out, long size) {        byte[] buffer = new byte[8192];   & nbsp;    long total = 0l;        int res;       & Nbsp;try {            while (true) {                res = in.read (buffer);                if (res = =-1) {                & nbsp;   break;                }                if (res > 0) {        & nbsp;           total + res;                     if (out! = nulL) {                        out.write (buffer, 0, res);                         system.out.println ("Size of File" + size + "Read Size" + total);       & nbsp;                update (total, size);                    }                }            }                            return total;        }catch (IOException e) {            return 0l;        }  finAlly {            try {                 in.close ();                out.close ();            } catch (IOException e) {            }        }    }     public Long Getbytesread () {        return this.bytesread;    }    public Long getcontentlength () {        return this.contentlength;    }    public String getfilename () {         return filename;    }    public void Setfilename (String fileName) { & nbsp      this.filename = filename;    }}

There is a problem with the use of the process, that is, do not know why ftpclient can not be instantiated. But it would be nice to change the name of FtpClient. * "Error: The Main method could not be found in class sun.net.ftp.FtpClient, please define the Main method as: public static void Main (string[] args).

Java Lightweight call FTP upload (Android available)

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.