17

How can I delete a file from an ftp server using a java program? I am successfully able to upload files on the ftp using the following code:

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    String s = "ftp://username:password@ftpclient:21/text.txt;type=i";
    URL u = new URL(s);
    URLConnection uc = u.openConnection();
    BufferedOutputStream bos = new BufferedOutputStream(uc.getOutputStream());
    bos.write(67);
    bos.close();
    System.out.println("Done");
}

But how do i delete files from this ftp server? Any help will be greatly appreciated......... Thanks in advance

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
awareeye
  • 3,051
  • 3
  • 22
  • 22

4 Answers4

25

You can use Apache FTPClient to do this and all other commands on FTP. Use it something like this:

...
FTPClient client = new FTPClient();
client.connect(host, port);
client.login(loginname, password);
client.deleteFile(fileNameOnServer);
client.disconnect();
...
alexblum
  • 2,198
  • 16
  • 13
  • 1
    +1 for javadoc link (plus you answered 54 seconds before me :) ) – pap Jul 22 '11 at 13:43
  • Thanks for ur answer. But i am looking for a way to do this without the ftpclient. Any help will be greatly appreciated – awareeye Jul 22 '11 at 15:16
  • Why would you want to implement the FTP protocol yourself, when there are numerous ready-built modules that do it for you? Don't re-invent the wheel. – pap Jul 26 '11 at 10:18
4

Check out Apache commons-net. It has an FTP client (among other stuff).

pap
  • 27,064
  • 6
  • 41
  • 46
2

The FTP command to remove a file is RMD, I think you could use:

String s = "ftp://username:password@ftpclient:21/text.txt;type=i";
URL u = new URL(s);
URLConnection uc = u.openConnection();
PrintStream ps = new PrintStream((uc.getOutputStream()));
ps.println("RMD " + <myFile>.getPath());
ps.close();
chepseskaf
  • 664
  • 2
  • 12
  • 41
1

Java's URL and URLConnection do not have support for deletion of resources. (I'm even surprised that upload works).

So you'll either have to use an FTP client library (like FTPClient from Apache Commons Net), or have to implement the necessary parts of the client side of the FTP protocol yourself.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210