Barun
Barun

Reputation: 1915

FTPClient cant get file listing from a directory name with space

I am using Apache FTPClient for getting files and sub-directory files listing. But it cant get listing of files from directory name with spaces. Here is an example - I tried it with two different directories:

    FTPClient client = new org.apache.commons.net.ftp.FTPClient();
    client.connect("ftp.domain.com");
    client.login("userid", "password");

    FTPFile[] names = client.listDirectories("ABC XYZ"); //Empty array
    FTPFile[] names2 = client.listDirectories("ABCXYZ"); //working

So directory name with spaces not returning anything. I tried to put "%20" and "+" at the place of space. Also I tried "\"ABC XYZ\"". But still is not working. Am I missing anything.

Upvotes: 6

Views: 9254

Answers (3)

Miki
Miki

Reputation: 1

Apparently while listFiles(String path), have a problem with paths which include spaces, other functions does not have a similar problem. What you need to do is simply to change the working directory and than use listFiles().

Something like this:

private FTPFile[] getDirectoryFiles(String dirPath) throws IOException
{
    String cwd = ftp.printWorkingDirectory();

    ftp.changeWorkingDirectory(dirPath);
    FTPFile[] files = ftp.listFiles();
    ftp.changeWorkingDirectory(cwd);

    return files;               
}

Upvotes: 0

Tryder
Tryder

Reputation: 256

This is an old one, but I recently ran into this problem and found a solution that seems to work for me. Use the escape character "\" to escape your spaces.

So for instance:

String path = "/Path/To/Folder With/Spaces";
path = path.replace(" ", "\\ ");
FTPFile[] listedDirectories = client.listDirectories(path);

Upvotes: 3

BackSlash
BackSlash

Reputation: 22243

I think this may be an Apache Commons issue, it doesn't work for me, in fact it might not work because spaces are interpreted as delimiters for command parameters. I couldn't find a solution to your problem, all i can do is suggest you a workaround:

FTPClient client = new org.apache.commons.net.ftp.FTPClient();
client.connect("ftp.domain.com");
client.login("userid", "password");

client.cwd("ABC XYZ");
FTPFile[] names = client.listDirectories(); //now this should work, it works for me
client.cdup();
FTPFile[] names2 = client.listDirectories("ABCXYZ"); //working

If you don't want to write this each time you have a directory with spaces in it's name, you can make a method that does it for you:

FTPFile[] listDirectories(String directory){
    if(directory.contains(" ")){
        client.cwd(directory);
        FTPFile[] listedDirectories = client.listDirectories();
        client.cdup();
        return listedDirectories;
    } else {
        return client.listDirectories(directory);
    }
}

Upvotes: 2

Related Questions