Java implementation ftp automatic upload download function "one" __java

Source: Internet
Author: User

For FTP automatic upload download, there will be deleted, create directories, FTP upload is a very good use of the common agreement, the basic online has a lot of content including tools, online also saw a lot of predecessors of the article, etc., is a very simple and practical things, Some people's FTP will use two jar package, I do not know the difference is where, after oneself wrote a ftputil, also used a jar, the concrete code is this.

Novice small white, FTP knowledge point is also a lot of, I have only tested upload feeling is still pretty fast, you see there is anything wrong with the place please advice.

Next, Win7 on the construction of FTP service

Jar:commons-net-3.3.jar

Package com.airchina.group.utils;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;

Import java.net.SocketException;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import Org.apache.commons.net.ftp.FTP;
Import org.apache.commons.net.ftp.FTPClient;


Import org.apache.commons.net.ftp.FTPReply; /** * FTP Client Tool class */public class Ftpclientutil {private static Log logger = Logfactory.getlog (ftpclient.
    
    Class);  
    
Private FtpClient ftpclient; public void Task () {//Dateutil.fullformatcurrenttime ();//} Public Ftpclientutil (String host, int PO  
    RT) Throws Exception {This (host, port, NULL, NULL);
        Public Ftpclientutil (string host, int port, string Username, string password) throws Exception {
        FtpClient = new FtpClient (); try {ftpclient.connect (hoSt, Port);
            int reply = Ftpclient.getreplycode (); if (!
                Ftpreply.ispositivecompletion (Reply)) {ftpclient.disconnect ();
                Logger.fatal ("FTP server refuses connection");
            throw new Exception ("FTP server Rejects connection"); } if (username!= null) {if (!ftpclient.login (username, password)) {FTPC
                    Lient.disconnect ();
                    Logger.fatal ("Login verification failure, please check the account and password is correct");
                throw new Exception ("Login verification failed, please check the account and password is correct");
            } ftpclient.setfiletype (Ftp.binary_file_type);
            The catch (SocketException e) {logger.fatal ("Cannot connect to the specified FTP server", e);
        throw new Exception (e);
            catch (IOException e) {logger.fatal ("Unable to connect to the specified FTP server with the specified user name and password", e);
        throw new Exception (e); 
     }/** * * @param path file must be stored on FTP @param input upload text * @throws IOException */public Boolean upload (String pathname, InputStream input) throws IOException {//Whether it is in the root directory  
        Lower Ftpclient.setfiletype (Ftp.binary_file_type);  
            if (Pathname.indexof ("/")!=-1) {String path = pathname.substring (0, Pathname.lastindexof ("/"));  
        mkdir (path);  
    Return Ftpclient.storefile (New String (Pathname.getbytes (), ftpclient.getcontrolencoding ()), input); 
     /** * Download the specified file from the FTP server, named LocalName * @param pathname * @param localname * @return  
        * @throws Exception */public boolean download (string pathname, String localname) throws Exception { String filename = localname!= null?  
  
        Localname:pathname. Substring (Pathname.lastindexof ("/") + 1);  
        if (filename = = NULL | | filename.isempty ()) {return false;  
        //Set Passive mode Ftpclient.enterlocalpassivemode (); //set to transmit Ftpclient.setfiletype (ftp.binary_file_type) in binary mode; if (Ftpclient.listfiles (Pathname.getbytes (), ftpclient.getcontrolencoding ()). Length = = 0) {Logge  
            R.fatal ("Download file does not exist");  
        throw new Exception ("Download file does not exist"); File TMP = new file (filename + "_tmp");  
        Temporary files file = new file (filename);  
        FileOutputStream output = null;  
        Boolean flag;  
            try {output = new FileOutputStream (TMP);  
            Flag = Ftpclient.retrievefile (New String (Pathname.getbytes (), ftpclient.getcontrolencoding ()), output);  
            Output.close ();  
                if (flag) {///download succeeded, rename temporary file.  
                Tmp.renameto (file);  
            System.out.println (File.getabsolutepath ());  
            The catch (FileNotFoundException e) {logger.fatal ("Download file failed", E);  
        throw new Exception (e);  
           finally { Output.close ();  
    return flag;  /** * Delete Files only, if delete empty directory please use the following method: <code> * getftpclient (). RemoveDirectory (String pathname) * </code> Reference * {@link org.apache.commons.net.ftp.FTPClient ftpclient} * * @param pathname * Returns True @return a successful deletion, or False if the file does not exist * @throws IOException */public boolean Delete (String path Name) throws IOException {return ftpclient.deletefile (new String (pathname.getbytes), Ftpclient.getcontrolencodi  
    Ng ())); /** * Changes the current directory to pathname, "/" represents the root directory * * @param pathname * path name * @return if The change succeeds back to True otherwise returns false * @throws IOException */public boolean changeworkingdirectory (String pathname) throw S IOException {return ftpclient.changeworkingdirectory (new String (Pathname.getbytes (), ftpclient.getcontrolencod  
    ing ()); }/** * @return {@link org.apache.commons. Net.ftp.FTPClient FtpClient} object/Public ftpclient getftpclient () {return this.ftpclient; 
     }/** * @param ftpclient * {@link org.apache.commons.net.ftp.FTPClient ftpclient} object  
    */public void setftpclient (FtpClient ftpclient) {this.ftpclient = ftpclient;  
    public void Close () throws Exception {Ftpclient.disconnect (); /** * * * @param pathname * The directory path you want to create can be a relative path or a path ("/") * @return If you successfully create the mesh  Record returns TRUE or False if the directory already exists (returns false) * @throws IOException/public boolean mkdir (String pathname) throws  
            IOException {try{ftpclient.setcontrolencoding ("iso-8859-1"); Note that if encoding is not encoded, the Chinese directory cannot create a return ftpclient.makedirectory (new String (Pathname.getbytes (), Ftpclient.getcontrolenc	
    	Oding ()));
    		}catch (Exception ex) {ex.printstacktrace ();
    	return false;  }
          
    }
  
}  
 

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.