Pages Navigation Menu

Coding is much easier than you think

Delete a file from FTP Server


 
In this section you will learn how to delete file from FTP server using java.

Delete File :

FtpClient class provides method to delete existing file from ftp server.

boolean deleteFile(String pathname) :This method is of boolean type. If file is deleted successfully, it will return true. If file doesn’t exist then this method return false. It throws FTPConnectionClosedException if ftp server connection is already closed. It also throws IOException if there is any I/O problem at the time of server communication.

Example :

In this example we are deleting file named “File.doc” which belongs to the FTP server. If this file doesn’t exist in the server then deleteFile() method will return false.

File : FtpDeleteDir
 

import java.io.IOException;

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

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

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

			boolean deleted = ftpclient.deleteFile(fileToRemove);
			if (deleted) {
				System.out.println("File is removed successfully.");
			} else {
				System.out.println("Fail does not exist.");
			}
		} catch (FTPConnectionClosedException exp) {
			exp.printStackTrace();
		} finally {
			try {
				ftpclient.disconnect();
			} catch (FTPConnectionClosedException e) {
				System.out.println(e);
			}
		}
	}
}