Search code examples
apache-commons-netftps

How do I get the file/folder path using Apache Commons net FTPS Client


I am using Apache commons ftps client to connect to an ftps server. I have the remote file path which is a directory. This directory contains a tree of sub-directories and files. I want to get the path for each file or folder. Is there any way I can get this property? Or if there is any way I could get the parent folder path, I could concatenate the file name to it.


Solution

  • I am currently using below function to get path and size of all files under a certain directory. It gets all the file in current directory and check if it is a directory or file. If it is a directory call recursively until end of the tree, if it is a file save the path and size. You may not need these "map" things you can edit according to your needs.

    Usage:

    getServerFiles(ftp,"") // start from root
    

    or

    getServerFiles(ftp,"directory_name") // start from given directory
    

    Implementation:

    def getServerFiles(ftp: FTPClient, dir: String): Map[String, Double] = {
        var fileList = Array[FTPFile]()
        var base = ""
        if (dir == "") {
          fileList = ftp.listFiles
        } else {
          base = dir + "/"
          fileList = ftp.listFiles(dir)
        }
        fileList.flatMap {
          x => if (x.isDirectory) {
            getServerFiles(ftp, base + x.getName)
          } else {
            Map[String, Double](base + x.getName -> x.getSize)
          }
        }.toMap
      }