Share on Google+Share on Google+

Delete a file from FTP Server

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

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 "FtpTutorial.txt" which belongs to the FTP server. If this file doesn't exist in the server then deleteFile() method will return false.

Here is your code :



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

			if (result == true) {
				System.out.println("Successfully logged in!");
			} else {
				System.out.println("Login Fail!");
			String fileToRemove = "/FtpTutorial.txt";

			boolean deleted = client.deleteFile(fileToRemove);
			if (deleted) {
				System.out.println("File is removed successfully.");
			} else {
				System.out.println("Fail to delete the file.It may not exist.");
		} catch (FTPConnectionClosedException e) {
		} finally {
			try {
			} catch (FTPConnectionClosedException e) {

Output :

Successfully logged in!
File is removed successfully.


Posted on: December 7, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Delete a file from FTP Server  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
December 11, 2012
Delete a readonly file from FTP Server

Using the deleteFile() i am not able to delete a file in the FTP server which has the readonly attribute set. Please suggest a solution delete the readonly file by changing the attribute of the FTPFile or by any other way using java 1.5.