Uploading and downloading files to FTP in Java

Source: Internet
Author: User

A recent project has a lot to do with FTP, often need to upload to FTP, download files, now summarize public methods.

Upload

/*** File Upload * *@paramIP * Host *@paramPort * Ports *@paramuserName * User name *@paramPassWord * Password *@paramLocalPath * Upload files on Local disk path *@paramFileName * File name *@paramremotepath * File to upload the path to the FTP server *@throwsException*/     Public StaticBoolean fileftpupload (String IP,intport, String userName, String PassWord, String LocalPath, String fileName, String remotepath) /c0>throwsException {ftpclient ftp=NewFtpClient ();//Creating Client ObjectsInputStream local =NULL; BooleanFlag =false; Try{checkisexsitfile (LocalPath, fileName);//determine if the file is in the local path or notSocketAddress address =Newinetsocketaddress (IP, port); Ftp.connect (IP, port);//ConnectionFtp.login (UserName, PassWord);//LoginLog.info ("FTP server connection, login successful, address:" +address); //Check that the upload path exists if there is no return false            BooleanFlag1 =ftp.changeworkingdirectory (RemotePath); if(!Flag1) {                //Create an uploaded path this method can only create a single level directory, where if/home/ftpuser exists you can create an image//ftp.makedirectory (path);                Throw NewException ("The file directory is not specified on the FTP server, please create first:" +RemotePath); }            //Specify the upload pathftp.changeworkingdirectory (RemotePath); //Specifies the type of file to upload the binary fileFtp.setfiletype (Ftp.binary_file_type); //Read local fileFile File =NewFile (localpath + "\ \" +fileName); Local=Newfileinputstream (file); //The first argument is a file nameFtp.storefile (File.getname (), local); Log.info ("Upload succeeded"); Flag=true; } Catch(SocketException e) {log.info ("Upload failed" +e); Flag=false;        E.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally {            Try {                //Close File StreamLocal.close (); //Exitftp.logout (); //Disconnect ConnectionFtp.disconnect (); } Catch(IOException e) {e.printstacktrace (); }        }        returnFlag; }

Before uploading a file, you need to determine if there are any files specified below the disk, and the method is as follows:

/** * Determine if file path has no specified file *  * @param filePath *            generated file name * @param filename *            file name * @return whether to create a successful, success returns True */public static void Checkisexsitfile (String filePath, String fileName) {file Dirfile = new File (filePath);//Folder object try {file[] File s = dirfile.listfiles (); Boolean bl = false;for (File file1:files) {if (Filename.equals (File1.getname ())) {bl = True;break;}} If the file in the folder does not exist, the error if (!BL) {throw new Exception ("File path does not specify the upload file");}} catch (Exception e) {e.printstacktrace ();}}

Note that you must first switch to the current directory before uploading, that is, this line

Specify the upload path ftp.changeworkingdirectory (remotepath);

You also need to specify the type of upload file

Specifies the type of upload file binary file Ftp.setfiletype (ftp.binary_file_type);

Download

/*** FTP Download file * *@paramIP *@paramPort *@paramUserName *@paramPassWord *@paramLocalPath *@paramRemotePath *@paramfilecontainsname * file contains name *@return     * @throwsException*/     Public StaticString Fileftpdown (String IP,intport, String userName, String PassWord, String LocalPath, String RemotePath, String Filecontain SName)throwsException {ftpclient ftpclient=NewFtpClient ();//Creating Client ObjectsString fileName = ""; SocketAddress Address=Newinetsocketaddress (IP, port); Ftpclient.connect (IP, port);//Connection        BooleanLogin = Ftpclient.login (UserName, PassWord);//Login        if(login) {Try{log.info ("FTP server connection, login successful, address is:" +address); Ftpclient.enterlocalpassivemode ();//open a port to transfer dataftpfile[] fs = Ftpclient.listfiles (RemotePath);//fs for all file collections under RemoteFile                 for(Ftpfile ff:fs) {String F=NewString (Ff.getname (). GetBytes ("Iso-8859-1"),                            "Utf-8"); if(F.contains (Filecontainsname)) {//use contains when file name is indeterminateFile LocalFile =NewFile (LocalPath + "\ \" + f);//an object was created on a locally specified pathOutputStream is =NewFileOutputStream (LocalFile); Ftpclient.changeworkingdirectory (RemotePath);//set the path where the download file is relative to the remote FTP root directoryFtpclient.setfiletype (Ftp.binary_file_type);//set the transport type before you begin downloading filesFtpclient.retrievefile (Ff.getname (), is);                        Is.close (); FileName=F; }                     Break; }            } Catch(IOException e) {e.printstacktrace (); } finally {                if(ftpclient.isconnected ()) {Try{ftpclient.disconnect (); } Catch(IOException IoE) {}}} } Else{log.info ("FTP Server connection, Login failed"); }        returnFileName; }

  

  

Uploading and downloading files to FTP in Java

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.