Delete a file/folder from an FTP server in Java

To delete an existing file in the FTP server using the Apache Commons Net API, one can use the method deleteFile() of the FTPClient:

public boolean deleteFile(String pathname) throws IOException:  this method will issue a command to the FTP server that deletes the path of the remote file specified in the parameter pathname. This method returns true if the remote file is successfully deleted, otherwise false if the file does not exist or it is a directory. This method raises an exception FTPConnectionClosedException in case the connection to the server is currently closed, or IOException if a read/write error occurs while communicating with the server.

To use the Apache Commons Net API, you must download it from  http://commons.apache.org/net/download_net.cgi  and add the .jar file to your classpath.

To illustrate the usefulness of the deleteFile(), we'll work with an example that:
  • Log in to the FTP server.
  • Delete the file on the server.
  • Disconnect from the server.
Here is an example of how to use the deleteFile():

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

public class deleteFileFTP {

public static void main(String[] args) {
String server = "server name or address";
int port = 21;
String username = "username";
String password = "password";

FTPClient ftpClient = new FTPClient();
try {

ftpClient.connect(server, port);

int response = ftpClient.getReplyCode();
if (! FTPReply.isPositiveCompletion(answer)) {
System.out.println("Connection failed");
return;
}

boolean res = ftpClient.login(username, password);

if (res==false) {
System.out.println("Failed Server Identification");
return;
}
String fileToDelete = "/music/Symphonie.wma";

boolean isDeleted = ftpClient.deleteFile(fileToDelete);

if (isDeleted==true) {
System.out.println("The file has been successfully deleted");
} else {
System.out.println("Unable to delete file");
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
e.g.printStackTrace();
} finally {
// disconnect from the server
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
After compiling and running the program, the terminal displays that the deletion was successful:

The file was successfully deleted