Delete file from Ftp server

bkulit
bkulit used Ask the Experts™
on
I'm using sun.net.ftp.* for ftp downloading and uploading but cannot find a way to delete a file from an ftp server. Is there a way I can delete the file after I have downloaded it?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
sun.net.ftp.FtpClient c;
c.sendServer("DELE <file>");
if (c.readServerResponse() != 250) // error
Commented:
There is no method in FtpClient to delete a file on the server. However, you can use the FtpClient.issueCommand() method to issue the FTP DELE command. This method is protected, so you need to subclass FtpClient:

public class CustomFtpClient extends FtpClient {

 public CustomFtpClient(String host) throws IOException {
   super(host);
 }

 public CustomFtpClient(String host, int port) throws IOException {
   super(host, port);
 }

 public CustomFtpClient() {
   super();
 }

 public void delete(String fileName) throws IOException {
   issueCommand("DELE " + fileName);
 }
}

Notice that we created a new method called delete(). delete() simply calls the issueCommand() method with the FTP DELE command and the name of the file to be deleted. If the delete is not successful, an exception will be thrown by the issueCommand() method. For example, if the file does not exist on the server, a FileNotFoundException (a subclass of IOException) will be thrown.

To use CustomFtpClient is easy:

try {
 CustomFtpClient ftpClient = new CustomFtpClient("host");
 ftpClient.login("userid", "password");
 String fileName = "file_to_be_deleted.txt";
 ftpClient.delete(fileName);
} catch (IOException ioException) {
 ioException.printStackTrace();
}

Commented:
did you try what I suggested?
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Commented:
Hi Venci75,

I tried your suggestion, but the program blocks forever when readServerResponse() is called.

By the way, do you have the URL to any documentation on this unofficial FTP API?

Commented:
aha - should be:
c.sendServer("DELE <file>\r\n");

no - I use jad :))

Commented:
I tried again, and it works this time. I guess if you had posted a workable code, you would have gotten the points instead. :)

Author

Commented:
Venci75: yes i've tried your suggestion but the program hangs when executing sendServer command.

Commented:
That's probably because you did not end the command line with "\r\n". This is required, according to the FTP specification. The FTP server program will wait until it receives these characters.

Author

Commented:
It's now working. Thanks guys!!!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial