Pages Navigation Menu

Coding is much easier than you think

Remove Directory on FTP Server

Remove Directory on FTP Server

 
In this section you will learn how to delete directory on FTP server using java.

To delete directory on ftp server FTPClient class provides removeDirectory() method. Directory is removed only if it is empty.

boolean removeDirectory(String name) : It returns boolean value. True value represents that the directory is removed successfully. It returns false if this method fail to delete the specified directory.

Example :

In this example we are deleting directory “/ftpNewDir” by using removeDirectory() of FTPClient class.

 

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import java.io.IOException;

class FtpDeleteDirectry {
	public static void main(String[] args) throws IOException {
		FTPClient client = new FTPClient();
		boolean result;
		try {
			client.connect("localhost");
			result = client.login("admin", "admin");

			if (result == true) {
				System.out.println("Logged in Successfully !");
			} else {
				System.out.println("Login Fail !");
			}
			String dirToRemove = "/ftpNewDir";

			boolean deleted = client.removeDirectory(dirToRemove);
			if (deleted) {
			System.out.println("The directory was removed successfully.");
			} else {
				System.out.println("File cannot be deleted.");
			}
		} catch (FTPConnectionClosedException e) {
			e.printStackTrace();
		} finally {
			try {
				client.disconnect();
			} catch (FTPConnectionClosedException e) {
				System.out.println(e);
			}
		}
	}
}

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.