![](/img/trans.png)
[英]Apache Commons Net FTPClient Will Not Execute listFiles()
[英]Apache Commons Net FTPClient and listFiles()
任何人都可以向我解释以下代码有什么问题吗? 我尝试了不同的主机,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);
找到了!
问题是您想在连接后但在登录之前进入被动模式。 您的代码对我没有任何返回,但这对我有用:
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
仅使用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());
}
通常匿名用户不需要密码,试试
client.login("anonymous", "");
对我来说,当我在调用ftpClient.listFiles()
之前使用ftpClient.enterLocalPassiveMode()
时它起作用了。 这是完整的代码:
final List<String> files = new ArrayList<>();
try {
ftpClient.enterLocalPassiveMode();
String[] f = null;
if (parentDir.isEmpty()) {
f = ftpClient.listNames();
}else{
f = ftpClient.listNames(parentDir);
}
for (String s :f ) {
files.add(s);
}
} catch (IOException e) {
e.printStackTrace();
postError(e.getMessage()!= null?e.getMessage():e.toString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.