Apache Commons Net FTPClient and listFiles()

2022-09-01 02:52:43

任何人都可以解释以下代码有什么问题吗?我尝试了不同的主机,FTPClientConfigs,它可以通过firefox / filezilla正确访问...问题是我总是得到空的文件列表,没有任何例外(files.length == 0)。我使用与Maven一起安装的commons-net-2.1.jar。

    FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_L8);

    FTPClient client = new FTPClient();
    client.configure(config);

    client.connect("c64.rulez.org");
    client.login("anonymous", "anonymous");
    client.enterRemotePassiveMode();

    FTPFile[] files = client.listFiles();
    Assert.assertTrue(files.length > 0);

答案 1

找到了!

问题是您希望在连接后进入被动模式,但在登录之前。您的代码对我没有任何返回,但这对我有用:

import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPFile;

public class BasicFTP {

    public static void main(String[] args) throws IOException {
        FTPClient client = new FTPClient();
        client.connect("c64.rulez.org");
        client.enterLocalPassiveMode();
        client.login("anonymous", "");
        FTPFile[] files = client.listFiles("/pub");
        for (FTPFile file : files) {
            System.out.println(file.getName());
        }
    }
}

给我这个输出:

c128
c64
c64.hu
incoming
plus4

答案 2

只使用对我不起作用。enterLocalPassiveMode()

我使用了以下代码,这有效。

    ftpsClient.execPBSZ(0);
    ftpsClient.execPROT("P");
    ftpsClient.type(FTP.BINARY_FILE_TYPE);

完整的示例如下,

    FTPSClient ftpsClient = new FTPSClient();        

    ftpsClient.connect("Host", 21);

    ftpsClient.login("user", "pass");

    ftpsClient.enterLocalPassiveMode();

    ftpsClient.execPBSZ(0);
    ftpsClient.execPROT("P");
    ftpsClient.type(FTP.BINARY_FILE_TYPE);

    FTPFile[] files = ftpsClient.listFiles();

    for (FTPFile file : files) {
        System.out.println(file.getName());
    }

推荐