Delete a file from FTP Server

Ads
 

Delete a file from FTP Server

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

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 :

import java.io.IOException;

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

class FtpDeleteDir {
	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("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) {
			e.printStackTrace();
		} finally {
			try {
				client.disconnect();
			} catch (FTPConnectionClosedException e) {
				System.out.println(e);
			}
		}
	}
}

Output :

Successfully logged in!
File is removed successfully.

Ads

Ads