In this article, we are going to develop an example of how to remove a non-empty directory (which includes sub directories and files) on a remote FTP server, using API of the Apache Commons Net library.

To delete all content of a non-empty directory, it’s important to list all content of the directory, its sub directories, sub directories of sub directories, and so on (listing recursively). The solution is a combination of the techniques which are described in the following articles:

For the purpose of reusability, we implement a static method in a utility class as follows:

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

/**
 * This utility class implements a method that removes a non-empty directory
 * on a FTP server.
 * @author www.codejava.net
 */
public class FTPUtil {

	/**
	 * Removes a non-empty directory by delete all its sub files and
	 * sub directories recursively. And finally remove the directory.
	 */
	public static void removeDirectory(FTPClient ftpClient, String parentDir,
			String currentDir) throws IOException {
		String dirToList = parentDir;
		if (!currentDir.equals("")) {
			dirToList += "/" + currentDir;
		}

		FTPFile[] subFiles = ftpClient.listFiles(dirToList);

		if (subFiles != null && subFiles.length > 0) {
			for (FTPFile aFile : subFiles) {
				String currentFileName = aFile.getName();
				if (currentFileName.equals(".") || currentFileName.equals("..")) {
					// skip parent directory and the directory itself
					continue;
				}
				String filePath = parentDir + "/" + currentDir + "/"
						+ currentFileName;
				if (currentDir.equals("")) {
					filePath = parentDir + "/" + currentFileName;
				}

				if (aFile.isDirectory()) {
					// remove the sub directory
					removeDirectory(ftpClient, dirToList, currentFileName);
				} else {
					// delete the file
					boolean deleted = ftpClient.deleteFile(filePath);
					if (deleted) {
						System.out.println("DELETED the file: " + filePath);
					} else {
						System.out.println("CANNOT delete the file: "
								+ filePath);
					}
				}
			}

			// finally, remove the directory itself
			boolean removed = ftpClient.removeDirectory(dirToList);
			if (removed) {
				System.out.println("REMOVED the directory: " + dirToList);
			} else {
				System.out.println("CANNOT remove the directory: " + dirToList);
			}
		}
	}
}
Notice that the method removeDirectory() is using recursive algorithm, which invokes itself if the file being listed is also a directory. That allows the method to work with directory structure in any depth level (only limited to the memory).

Here is a test program that connects to a FTP server, remove the directory “/Test” and disconnects from the server:

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;

/**
 * This program demonstrates how to remove a non-empty directory on a FTP
 * server, using Apache Commons Net FTP library.
 *
 * @author www.codejava.net
 *
 */
public class FTPRemoveNonEmptyDir {

	public static void main(String[] args) {
		String server = "www.codejava.net";
		int port = 21;
		String user = "username";
		String pass = "password";

		FTPClient ftpClient = new FTPClient();

		try {
			// connect and login to the server
			ftpClient.connect(server, port);
			ftpClient.login(user, pass);

			// use local passive mode to pass firewall
			ftpClient.enterLocalPassiveMode();

			System.out.println("Connected");

			String dirPath = "/Test";

			FTPUtil.removeDirectory(ftpClient, dirPath, "");

			// log out and disconnect from the server
			ftpClient.logout();
			ftpClient.disconnect();

			System.out.println("Disconnected");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
 

NOTES:Remember to change the server address, username and password according to your own FTP account.

Compile the utility class:

javac -cp commons-net-VERSION.jar FTPUtil.java

Compile the test program:

javac -cp commons-net-VERSION.jar;. FTPRemoveNonEmptyDir.java



Run the test program:

java -cp commons-net-VERSION.jar;. FTPRemoveNonEmptyDir

Where commons-net-VERSION.jar is runtime library of the Apache Commons Net. You can download the latest distribution of this library here.

Supposing the directory “/Test” on the FTP server we want to remove has the following structure:

directory structure to delete

Then the program would produce the following output:

output of program to remove non-empty directory

Related Java FTP Tutorials:

 

Other Java FTP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (FTPRemoveNonEmptyDir.java)FTPRemoveNonEmptyDir.java[Test program]1 kB
Download this file (FTPUtil.java)FTPUtil.java[Utility class]1 kB

Add comment

   


Comments 

#7Henrry2022-11-12 09:54
Muchisimas gracias todos tus algoritmos me han sido de gran utilidad saludos desde bolivia
Quote
#6Nam2016-06-24 03:56
Quoting Silviu:
It doesn't work, no errors, just not working. I appears in the console "connected" and just then "disconnected" and the directory is still there.. :( if you could help me please.

Is that directory non-empty?
Quote
#5Silviu2016-06-17 09:23
It doesn't work, no errors, just not working. I appears in the console "connected" and just then "disconnected" and the directory is still there.. :( if you could help me please.
Quote
#4Maxwell Knoxx2015-07-14 07:59
That's good..
Works fine...

Thanks!
Quote
#3abhiram2014-09-18 07:40
Hi Ahmed Wahba,
could you please tell me in details which lines to add after if empty condition,
Quote