how to delete file from ftp server using java?

awareeye picture awareeye · Jul 22, 2011 · Viewed 23.6k times · Source

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

Answer

alexblum picture alexblum · Jul 22, 2011

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();
...