Uploading files with ftp4j jar Package class

Source: Internet
Author: User
Tags create directory ftp login ftp client
Import it.sauronsoftware.ftp4j.FTPClient;
Import it.sauronsoftware.ftp4j.FTPException;

Import It.sauronsoftware.ftp4j.FTPFile;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.net.URISyntaxException;
Import Java.net.URL;
Import Java.util.Arrays;
Import Java.util.Comparator;
Import java.util.Properties;

Import Java.util.logging.Logger;


Import Org.apache.commons.lang.StringUtils;
	public class Ftp4jftpclient {private static ftp4jftpclient ftp;
	/** * FTP Service addresses/private static String address;
	/** * FTP Login username */private static String USERNAME;
	
	/** * FTP Login Password * * private static String PASSWORD;
		static {Properties Pro = new properties ();
		FileInputStream in; try {String FilePath = Ftp4jFtpClient.class.getClassLoader (). GetResource ("/"). Touri (). GetPath () + "Ftpserver.propert
			IES ";
			
			in = new FileInputStream (FilePath);
			
	Pro.load (in);		Address = Pro.getproperty ("ftp_server_address");
			USERNAME = Pro.getproperty ("Ftp_server_username");
			
			PASSWORD = Pro.getproperty ("Ftp_server_password");
			
		In.close ();
		catch (FileNotFoundException e) {e.printstacktrace ();
		catch (IOException e) {e.printstacktrace ();
		catch (URISyntaxException e) {e.printstacktrace (); }/** * Construction method/Private Ftp4jftpclient () {}/** * Instantiate Object * * @return/public static FTP4JFTPC
		Lient getinstance () {if (FTP = null) {FTP = new ftp4jftpclient ();
	return FTP; /** * Get FTP client Object * * @return * @throws Exception/private FtpClient getclient () throws Exception {Ftpc
		Lient client = new FtpClient ();
		Client.setcharset ("Utf-8");
		Client.settype (ftpclient.type_binary);
		URL url = new URL (ftp4jftpclient.address); int port = Url.getport () < 1?
		
		21:url.getport ();
		Client.connect (Url.gethost (), port); Client.login (Ftp4jftpclient.username, ftp4jftpClient.password);
	return client; /** * Logoff Client Connection * * @param clients * FTP client Object * @throws Exception/private void Logout (Ftpclien
			T-client) throws Exception {if (client!= null) {try {//Some FTP servers do not implement this feature, error if not implemented Client.logout ();//Exit Login
			catch (Ftpexception fe) {} catch (Exception e) {throw e;
				finally {if (client.isconnected ()) {//Disconnect client.disconnect (TRUE); /** * Create directory * * @param client * FTP client Object * @param dir * directory * @throws Ex ception * * private void Mkdirs (FtpClient client, String dir) throws Exception {if (dir = null | | dir== "") {Retu
		Rn
		dir = Dir.replace ("//", "/");
		string[] dirs = Dir.split ("/");
		String path = "";
			
			for (int i = 0; i < dirs.length i++) {path + dirs[i] + "/"; if (!isdirexist (Client,path)) {client.createdirectory (path);//Create Directory Client.changedirector Y (path);//Enter the created meshRecord}}/** * Get FTP directory * * @param URL * Original FTP directory * @param dir * directory * @re 
		Turn * @throws Exception * * Private URL getURL (url url, String dir) throws Exception {string path = Url.getpath ();
		if (!path.endswith ("/") &&!path.endswith ("//")) {path + = "/";
		dir = Dir.replace ("//", "/");
		if (Dir.startswith ("/")) {dir = dir.substring (1);
		Path + dir;
	return new URL (url, path);  /** * Get FTP directory * * @param dir * directory * @return * @throws Exception/private URL GetURL (String
	Dir) throws Exception {return GetURL (new URL (ftp4jftpclient.address), dir); /** * To determine if a file or directory exists * * @param client * FTP client Object * @param dir * file or directory * @return * @throws Exception * * Private Boolean exists (FtpClient client, String dir) throws Exception {return Getfiletype (clien
		
	T, dir)!=-1; Check whether the directory exists private static Boolean isdirexist (FtpClient client,String dir) {try {client.changedirectory (dir);
        catch (Exception e) {return false;
    return true; /** * To determine whether the current file or directory * * @param client * FTP client Object * @param dir * file or directory * @return-1
		, file or directory does not exist 0, file 1, directory * @throws Exception */private int Getfiletype (ftpclient client, String dir) throws Exception {
		ftpfile[] files = null;
			
		try {files = client.list (dir);
		catch (Exception e) {return-1;
		} if (Files.length > 1) {return ftpfile.type_directory;
			else if (files.length = 1) {Ftpfile f = files[0];
			if (f.gettype () = = ftpfile.type_directory) {return ftpfile.type_directory;
			String Path = dir + "/" + f.getname ();
				try {int len = client.list (path). length;
				if (len = = 1) {return ftpfile.type_directory;
				else {return ftpfile.type_file;
			The catch (Exception e) {return ftpfile.type_file; }} else {Try {client.changedirectory (dir);
				Client.changedirectoryup ();
			return ftpfile.type_directory;
			catch (Exception e) {return-1; }}/** * upload file or directory * * @param dir * target file * @param del * Delete source file, default to False * @para M file * or directory object array * @throws Exception */public void upload (String dir, Boolean del, File ... files) thr
		oWS Exception {if (Stringutils.isempty (dir) | | | files = NULL | | files.length==0) {return;
		} ftpclient client = null;
			
			try {client = Getclient (); Mkdirs (client, dir); Create folder for (File file:files) {if (File.isdirectory ()) {//Upload directory Uploadfolder (client, GetURL (dir), fil
				E, Del);
					
					else {String current1 = Client.currentdirectory ();
					
					Client.changedirectory (dir);
					
					Client.changedirectory ("/" + dir + "/");
					
					String Current2 = Client.currentdirectory (); Client.upload (file); Upload file if (del) {//delete source file. Delete ();
		}}} finally {logout (client); }/** * Upload file or directory * * @param dir * target file * @param files * File or directory object array * @throws Except
	Ion */public void upload (String dir, File ... files) throws Exception {upload (dir, false, files);
	 /** * Upload file or directory * * @param dir * target file * @param del * Delete source file, default to False * @param path * File or directory path array * @throws Exception */public void Upload (String dir, Boolean del, string ... paths) throw
		S Exception {if (dir==null | | paths = NULL | | | paths.length ==0) {return;
		} file[] files = new File[paths.length];
		for (int i = 0; i < paths.length i++) {files[i] = new File (paths[i));
	} Upload (dir, del, files); 
	 /** * Upload file or directory * * @param dir * target file * @param paths * File or directory path array * @throws Exception
	*/public void Upload (string dir, string ... paths) throws Exception {upload (dir, false, paths); }
	/** * Upload Directory * * @param client * FTP client Object * @param parenturl * parent Node URL * @param file * Directory * @throws Exception/private void Uploadfolder (FtpClient client, URL parenturl, file file, bool
		Ean del) throws Exception {client.changedirectory (Parenturl.getpath ()); String dir = File.getname ();
		The current directory name URL url = GetURL (ParentURL, dir); if (!exists (client, Url.getpath ()) {//Determine if the current directory exists client.createdirectory (dir);//Create Directory} client.changedirectory (d
		IR); file[] files = file.listfiles ();
			Gets all files and directories for the current folder for (int i = 0; i < files.length; i++) {file = Files[i];
			if (File.isdirectory ()) {//If it is a directory, recursively uploads the Uploadfolder (client, URL, file, Del);
				else {//If it is a file, upload client.changedirectory directly (Url.getpath ());
				Client.upload (file);
				if (DEL) {//delete source file File.delete (); /** * Delete files or directories * * @param dir * file or directory array * @throws Exception/public void Delete (S Tring...
		dirs) throws Exception {if (dirs = = NULL | | dirs.length ==0) {return;
		} ftpclient client = null;
			try {client = Getclient ();
			int type =-1;  for (String dir:dirs) {client.changedirectory ("/");//switch to the root directory type = getfiletype (client, dir);//Get the current type if (type = = 0)
				{//delete file Client.deletefile (dir);
				else if (type = = 1) {//delete directory DeleteFolder (client, GetURL (dir));
		}}} finally {logout (client); }/** * Delete directory * * @param client * FTP client object * @param URL * FTP URL * @throws Except
		Ion */private void DeleteFolder (ftpclient client, url url) throws Exception {String path = Url.getpath ();
		Client.changedirectory (path);
		ftpfile[] files = client.list ();
		String name = NULL;
			for (Ftpfile file:files) {name = File.getname (); Excludes hidden directories if ("."). Equals (name) | | "..".
			Equals (name)) {continue; } if (file.gettype () = = Ftpfile.type_directory) {//recursively deletes subdirectories DeleteFolder(Client, GetURL (URL, file.getname ());
			else if (file.gettype () = = Ftpfile.type_file) {//delete file Client.deletefile (File.getname ());
		} client.changedirectoryup (); Client.deletedirectory (Url.getpath ()); Delete current directory}/** * Download files or directories * * @param localdir * Local Storage directory * @param dirs * file or directory * @th Rows Exception */public void Download (string localdir, String ... dirs) throws Exception {if (Dirs==null | |
		Dirs.length ==0) {return;
		} ftpclient client = null;
			try {client = Getclient ();
			File Folder = new file (Localdir);
			if (!folder.exists ()) {//If the local folder does not exist, create folder.mkdirs ();
			int type =-1;
			String localpath = null;  for (String dir:dirs) {client.changedirectory ("/");//switch to the root directory type = getfiletype (client, dir);//Get the current type if (type = = 0)
					{//File LocalPath = Localdir + "/" + New File (dir). GetName ();
				Client.download (dir, New File (LocalPath)); else if (type = = 1) {//directory DownloAdfolder (Client, GetURL (dir), Localdir);
		}}} finally {logout (client); /** * Download Folder * * @param client * FTP client object * @param URL * FTP URL * @param locald IR * Local Storage directory * @throws Exception */private void Downloadfolder (ftpclient client, url url, String localdi
		R) throws Exception {String path = Url.getpath ();
		Client.changedirectory (path);
		Create the currently downloaded folder locally = new file (Localdir + "/" + New File (path). GetName ());
		if (!folder.exists ()) {folder.mkdirs ();
		} Localdir = Folder.getabsolutepath ();
		ftpfile[] files = client.list ();
		String name = NULL;
			for (Ftpfile file:files) {name = File.getname (); Excludes hidden directories if ("."). Equals (name) | | "..".
			Equals (name)) {continue; } if (file.gettype () = = Ftpfile.type_directory) {//recursively download subdirectory downloadfolder (client, GetURL (URL, File.getname ()), Lo
			CALDIR); else if (file.gettype () = = Ftpfile.type_file) {//download file Client.download (Name, new File (Localdir + "/" + name));
	} client.changedirectoryup (); /** * Get all Files under directory * * @param dir * directory * @return * @throws Exception/public string[] List (St
		Ring dir) throws Exception {ftpclient client = null;
			try {client = Getclient ();
			Client.changedirectory (dir);
			String[] values = Client.listnames (); if (values!= null) {//Sort the file (ignore case) Arrays.sort (values, new comparator<string> () {public int compare (
					String val1, String val2) {return val1.comparetoignorecase (VAL2);
			}
				});
		return values;
			catch (Ftpexception Fe) {//Ignore folder does not exist String mark = "code=550";
			if (fe.tostring (). IndexOf (Mark) = = 1) {throw FE;
		Finally {logout (client);
	Return to new string[0];
 }
	
	
	
}

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.