Home Java Javaftp Delete a file from FTP Server
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Delete a file from FTP Server

Advertisement
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.
Advertisement

Liked it!  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.

Posted on: December 7, 2012

Ask Questions?    Discuss: Delete a file from FTP Server  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Girish
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.
DMCA.com