To teach you to use ftpclient ftp file upload and download operations

Source: Internet
Author: User
Tags ftp connection ftp file getmessage response code ftp client free ftp free ftp client ftp transfer
Package com.ad.util;
Import Org.apache.commons.net.ftp.FTP;
Import org.apache.commons.net.ftp.FTPClient;
Import org.apache.commons.net.ftp.FTPReply;
Import Org.apache.commons.net.ftp.FTPFile;

Import Org.apache.commons.net.ftp.FTPListParseEngine;

Import Com.ad.adweb.system.GlobalConst;
Import Java.io.InputStream;
Import Java.io.FileOutputStream;
Import Java.io.File;

Import Java.util.Calendar;
 /** * <p> * title:ftputil * </p> * <p> * description:ftp operation of the tool class, through this class can complete the file to the designated FTP server upload and download. 
 * </p> * <p> * Copyright:copyright (c) 2007 * </p> * <p> * Company:routon * </p> *
 
	* @author Zhihui Zhou * @version 1.0 internalerror-->exception by Jiangyl * @2007.12.21/public class Ftputil {

	/** * Global Configuration Entry: FTP transfer mode: passive/active///private static String Configftpmode = null;

	/** * Global Configuration entry: Applet FTP transfer mode: passive/active *///private static String Configclientftpmode = null; /** * FTP Server IP address/private StrinG _ftpserver;

	/** * FTP Port * * private int _ftpport;

	/** * FTP Server valid login username */private String _username;

	/** * FTP Server valid login user password/private String _password;

	/** * Object instance of FTP client * * Private ftpclient _ftp;

	
	/** * FTP mode */private String ftpmode = null; Public Ftputil (String ftpserver, String userName, String password) throws Exception//{//try//{//Setftpserve
	R (Ftpserver);
	Setusername (UserName);
	SetPassword (password);
	//Initialize FTP client object instance//_ftp = new FtpClient ();
	}//catch (Exception ex)//{//throw new Exception (Ex.getmessage ());
	 }//}/** * constructor * * @param ftpserver FTP Server * String * @param userName Username * string  * @param password Password * String * @throws Exception Exception/public ftputil (string ftpserver, int port, string
			UserName, String password) throws Exception {try {setftpserver (ftpserver);
			Setusername (UserName); SetpasswoRD (password);

			This._ftpport = port;
		Initializes an FTP client object instance _ftp = new FtpClient ();
		The catch (Exception ex) {throw new Exception (Ex.getmessage ()); /** * Get the IP address of the FTP server * * @return Ftpserverip string/public string Getftpserver () {return _ftpserver
	; /** * Set FTP server IP address * * @param ftpserverip * String * @throws Exception/public void Setftpse
		RVer (String ftpserver) throws Exception {//Check the FTP server address entered, not allowed null. if (Ftpserver = null | | ftpserver.length () = 0) {throw new Exception ("FTP server IP address cannot be empty.
		");
	} _ftpserver = Ftpserver;
	/** * Get FTP server username * * @return userName String */public string GetUserName () {return _username; /** * Set the FTP server username * * @param userName * String * @throws Exception/public void Setusername (
		String userName) throws Exception {//Check the FTP server name entered and not allow null. if (UserName = null | | username.length () = 0) {throw new Exception ("Login User for FTP server")The name cannot be empty.
		");
	} _username = UserName;
	/** * Get the FTP server user login Password * * @return Password string/public string GetPassword () {return _password; /** * Set the FTP server user password * * @param password * String * @throws Exception/public void SetPassword
		(String password) throws Exception {//Check the FTP server user login password, not allow null. if (password = = NULL | | password.length () = 0) {throw new Exception ("The FTP server's logon user password cannot be null.
		");
	} _password = password;
	 /** * Upload files to the FTP server specified path * * @param ftppath * File Upload ftp path * @param inputstream * Upload file stream
	 * @return isuploadsuccessed Ture said upload success, sent a club to show that the upload failed. * @throws Exception */public boolean uploadfile (String ftppath, InputStream inputsteam) throws Exception {Boolean

		issuccessed = false; Login to FTP server with specified username and password (login _username, _password) {//Start uploading file _ftp.setfiletype ftp.

				Binary_file_type); if (_ftp.storefile (Ftppath, Inputsteam)) {issuccessed = true; else {throw new Exception ("File upload failed.")
				");
				} else {//Login failed issuccessed = false; throw new Exception ("user" + _username + "Landing FTP Server" + _password +) failed.
			");
		} catch (Exception ex) {throw new Exception (Ex.getmessage ());
		finally {ftpdispose ();
	return issuccessed; /** * Create a directory above the FTP server * * @param folderName * Directory Name * @return Boolean Create result True indicates success, FALSE indicates failure * @t

		Hrows Exception */public boolean createfolder (String folderName) throws Exception {Boolean issuccessed = false; Login to the FTP server with the specified username and password (login _username, _password) {//start creating the specified directory to the FTP server if (_ftp.makedire
				Ctory (FolderName)) {issuccessed = true; else {throw new Exception ("FTP folder creation failed.")
				");
				} else {//landing FTP failed issuccessed = false; throw new Exception ("user" + _username + "Landing FTP Server" + _password +) failed.
			");
} catch (Exception ex) {			throw new Exception (Ex.getmessage ());
		finally {ftpdispose ();
	return issuccessed; /** * Login to FTP server based on specified username and password * * @param username * Login Username * @param password * Login user password * @r Eturn isuploadsuccessed True indicates login success, false means login failed * @throws Exception/public boolean Login (string username, String pa

		ssWOrd) throws Exception {Boolean issuccessed = false;

			try {int reply = 0;

			Connect to the specified FTP server _ftp.connect (_ftpserver, This._ftpport);
			Check the response code for the FTP connection request to make sure the connection request succeeds or fails.
			Reply = _ftp.getreplycode (); if (!
				Ftpreply.ispositivecompletion (Reply)) {_ftp.disconnect ();
			throw new Exception ("FTP server Rejects connection."); Login to FTP server if (!_ftp.login (_username, _password)) {throw new Exception ("user" + _username +) login According to specified username and password FTP Server "+ _password +" failed.
			");

			}//Set FTP mode Setcurrentftpmode ();
		Issuccessed = true;
		catch (Exception e) {throw new Exception (E.getmessage ()); } return IsSuccessed; /** * Set FTP mode, priority order: 1 Ftpmode 2. Configftpmode 3.
		Commons-net lib default */private void Setcurrentftpmode () {String tmpftpmode = null;
		if (Ftpmode!= null && ftpmode.length () > 0) {tmpftpmode = Ftpmode; else if (globalconst.configftpmode!= null && GlobalConst.ConfigFtpMode.length () > 0) {tmpftpmode = G
		Lobalconst.configftpmode; 
				} if (Tmpftpmode!= null && tmpftpmode.length () > 0) {if (Tmpftpmode.equalsignorecase ("passive")) {
			_ftp.enterlocalpassivemode ();
			else if (tmpftpmode.equalsignorecase ("active")) {_ftp.enterlocalactivemode ();
		/** * Free FTP client/public void Ftpdispose () {try {//Logoff FTP client _ftp.logout ();
		catch (Exception e) {//If FTP logoff fails to do nothing, ignore exceptions.
		///If the connection to the FTP client is still present, disconnect.
			if (_ftp.isconnected ()) {try {_ftp.disconnect ();
			The catch (Exception ex) {//If disconnecting the FTP connection fails to do nothing, ignore the exception. }}/** * from FTPDownload file * * @param ftpfilename * source file name * @param locafilename * destination file name * @return Boolean True table The download file succeeded, False indicates that the download file failed * @throws Exception/public boolean downfile (String ftpfilename, String locafilename) throws

		Exception {Boolean issuccessed = false;
				try {if (Login (_username, _password)) {File File = new file (locafilename);

				FileOutputStream fos = new FileOutputStream (file);

				+ by Jiangyl @2008.7.6 _ftp.setfiletype (ftp.binary_file_type);
				issuccessed = _ftp.retrievefile (ftpfilename, FOS);
				Fos.close ();

				FILE = null;
				if (!issuccessed) {throw new Exception ("file" + ftpfilename + "Download failed.");
				} else {issuccessed = false; throw new Exception ("user" + _username + "Landing FTP Server" + _password +) failed.
			");
		} catch (Exception ex) {throw new Exception (Ex.getmessage ());
		finally {ftpdispose ();
	return issuccessed; /** * Provides a static method, called by the external Timer task module, to clear the expired data files on the FTP server* * @return int indicates the number of files successfully deleted * @throws Exception/public static void Clearftpexpiredfiles () throws Exception
		{Com.ad.util.FtpServerInfo ftpserver = com.ad.util.FtpServerInfo.getInstance (); Com.ad.util.FTPUtil ftputil = new Com.ad.util.FTPUtil (Ftpserver.getftp (). Getftpintip (), Ftpserver.getftp (). Getport (

		), Ftpserver.getftp (). Getupname (), Ftpserver.getftp (). GETUPPWD ());
	Ftputil.clearexpiredfiles ();
	 /** * According to the Web.xml configuration, the FTP server to clean up the expired data files, clean the directory has: Playbill, Terparam, Theme, Themepolicy * * * @return int indicates the number of files successfully deleted

		* @throws Exception */public int clearexpiredfiles () throws Exception {int deletenum = 0;
				try {if (Login (_username, _password)) {deletenum + = Deleteexpiredfiles ("Playbill");
				Deletenum + = Deleteexpiredfiles ("Terparam");
				Deletenum + = Deleteexpiredfiles ("theme");
			Deletenum + = Deleteexpiredfiles ("Themepolicy"); else {throw new Exception ("user" + _username + "Landing FTP Server" + _password +) failed.
		");	} catch (Exception ex) {throw new Exception (Ex.getmessage ());
		finally {ftpdispose ();
	return deletenum;
	 /** * Web.xml The expired data files on the FTP server based on the configuration in the * * * @param ftppathname * To be cleaned directory * @return int indicates the number of files successfully deleted  * @throws Exception */private int deleteexpiredfiles (String ftppathname) throws Exception {Boolean issuccessed =
		False
		int deletenum = 0;
		Calendar Dtnow = Calendar.getinstance ();
		Calendar dt = null;
		ftpfile[] files = null;
		Long T1 = System.currenttimemillis ();
		
		Long t2 =-1;
			try {//_ftp.changeworkingdirectory ("Themepolicy");

			string[] names = _ftp.listnames (); Paged access, using a parser accessible by auto-detect:ftplistparseengine engine = _ftp.initiatelistparsing (Ftppath
			
			Name); while (Engine.hasnext ()) {files = Engine.getnext;//' page size ' you want for (int i = 0; i < Files.le Ngth; i++) {//System.out.println (Files[i].getname () + "--" +fastdateFormat.getinstance ("YYYY-MM-DD//HH:mm:ss"). Format (Files[i].gettimestamp ());
					DT = Files[i].gettimestamp ();
					Dt.add (Calendar.month, Com.ad.adweb.system.ClearExpiredDataDao.ExpiredDataMonthDiff); The last few months of data are retained in the FTP server by default 1-month if (Dt.compareto (Dtnow) <= 0) {issuccessed = _ftp.deletefile (ftppathname
						
						+ "/" + files[i].getname ());
							if (issuccessed) {deletenum++; System.out.println ("DeleteFile ok!
						--"+ files[i].getname () +"--"+ fastdateformat.getinstance (" Yyyy-mm-dd HH:mm:ss "). Format (DT));
		}}//for} catch (Exception ex) {throw new Exception (Ex.getmessage ());
		} t2 = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("FTP Server expired data file cleanup--" + Ftppathname + "directory," + Deletenum + "files have been deleted, when" + (T2-T1) + "Ms.
		
		");
	return deletenum;
	/** * Get Ftpmode * @return string Ftpmode/public string Getftpmode () {return ftpmode; /** * Set Ftpmode * @param ftpmode FTpmode */public void Setftpmode (String ftpmode) {ftpmode = Ftpmode; ///**//* Get Configclientftpmode//* @return string Configclientftpmode/////public static string Getconfigcli Entftpmode ()//{//return configclientftpmode;//}/////**//* Set Configclientftpmode//* @param CONFIGCLIENTFTPM Ode Configclientftpmode////public static void Setconfigclientftpmode (String configclientftpmode)//{//CONFIGCLI
Entftpmode = Configclientftpmode;
/////**//* Get Configftpmode//* @return String Configftpmode/////public static String Getconfigftpmode () {//return configftpmode;//}////**//* Set Configftpmode//* @param configftpmode Configftpmode////Pub
 Lic static void Setconfigftpmode (String configftpmode)//{//Configftpmode = Configftpmode;//}}//End

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.