Search code examples
javaftpfilenamesapache-commons-net

checking a file starts with a name in ftp location using java


Before downloading a file needs check whether the file(file name starts) exist or not: I had a ftp location, it will generate a file in response to hitting a service(API). I need to check whether file exits or not in ftp location using a starting characters of file name because it will append some data at end of file name. Can any one help on this using java code with commons.net package


Solution

  • Use FTPFileFilter

    try {
        String filePattern = "prefix";
        FTPClient objFTPClient = new FTPClient();
        //objFTPClient - set username, password, host, etc...
        FTPFileFilter ftpFileFilter = new FTPFileFilter() {
            @Override
            public boolean accept(FTPFile ftpFile) {
                return ftpFile.getName().toLowerCase().startsWith(filePattern.toLowerCase());
            }
        };
        /* List of file that starts with your given prefix */
        FTPFile[] ftpFiles = objFTPClient.listFiles(remoteDirectory, ftpFileFilter);
    }catch(Exception ex){ 
        ex.printStackTrace();
    }finally{
        //close connection, etc....
    }