Search code examples
javaftpftp-client

Delete file by filename on FTP with Java


Is it possible to delete file by filename, without the extension. I'm using FTPClient to connect to my FTP server and work great. I can upload files only in 3 formats (.png, .jpg, .gif). In fact i could delete the file only if i specify the extension like that and work:

ftp.deleteFile("/"+productID+setFileName+".png");

But i want to delete the file no matter what is the extension of the file, only by file name. Thanks


Solution

  • How about the startsWith() function?

    org.apache.commons.net.ftp.FTPClient ftpClient=new FTPClient();  //instantiate the FTPClient
    FTPFile[] ftpFiles=ftpClient.listFiles();//get the list of files in the root directory of the FTP server
    for(FTPFile tempFtpFile:ftpFiles)
    {
      //go through the list of files and delete those that start with your required prefix
      String tempFtpFileName=tempFtpFile.getName();
      if(tempFtpFileName.startsWith(productID+setFileName))
       ftpClient.deleteFile(tempFtpFile.getName());
    }