Search code examples
javaftp-clientapache-commons-net

org.apache.commons.net.ftp.FTPClient listFiles always returns files from root directory irrespective of the pathname given in argument


listFiles in the class FTPClient is always returning the directories or files from the root directory, even when the path is given as argument.

public static void main(String[] args) {
    String server = "192.168.0.60";
    int port = 21;
    FTPClient ftpClient = new FTPClient();
    try {

        ftpClient.connect(server,port);
        ftpClient.enterLocalPassiveMode();
        ftpClient.login("anonymous", "");
        FTPFile[] files = ftpClient.listFiles("/StorageCard");
        for(FTPFile ftpFile: files) {
            System.out.println(ftpFile.getName());
        }
    } catch(IOException io) {
        io.printStackTrace();
    }
}

StorageCard is a directory inside the rootfolder

Output what I get is

  1. Network Internal Storage
  2. WinDrive
  3. StorageCard
  4. Application Data
  5. My Documents
  6. Program Files
  7. Windows
  8. .........

Solution

  • You should be changing working directory before using listFiles()

    ftpClient.changeWorkingDirectory("StorageCard");
    FTPFile[] files = ftpClient.listFiles();