Search code examples
filegrailsgroovyftp

How to check file Exist or not?


Here I'm trying to check whether the file exist or not.but the below code doesn't return anything and also get the error at this line

Error line : Boolean t = fileslist.Exists()

   start()
    def start(){
    def store;
    boolean success;
    def ftpClient = new FTPClient()
    ftpClient.connect(server)
    ftpClient.login(user,pass) 
     ftpClient.enterLocalPassiveMode()
     FTPFile[] fileslist = ftpClient.listFiles("/Sample.txt")
     ftpClient.setFileType(FTP.BINARY_FILE_TYPE)
     filelist.each{
          it.exists()
       }  
     ftpClient.disconnect() 

    }

Thanks


Solution

  • You can verify that a file exists by checking that the returned array is not empty:

    FTPFile[] fileslist = ftpClient.listFiles("/Sample.txt")
    
    if(fileslist)
        print "File exists"
    else(fileslist)
        print "File does not exist"
    

    Alternatively, you can check the results and find the name you're interested in:

    FTPFile[] fileslist = ftpClient.listFiles("/")
    
    def matchedFiles = Arrays.asList(fileslist).grep(it.name == 'Sample.txt')
    

    The below will return a list with matching file objects