2010-04-26 91 views
32

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

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); 
+0

任何错误讯息?不知道你的问题是什么! – Guillaume 2010-04-26 11:24:39

+0

问题是我总是得到空文件列表没有任何例外(files.length == 0)。问题已更新。 – 2010-04-26 11:31:25

+0

它在我的FTP服务器上正常工作,除了我不呼叫client.configure(...) – Guillaume 2010-04-26 11:40:43

回答

75

找到了!

你想要的东西连接后进入被动模式,但是在你登录之前进入。 你的代码返回没有我的,但是这对我的作品:

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 
+0

谢谢。我用另一个lib解决了这个问题。 – 2011-03-03 18:44:44

+1

(关于BTW评论:'Assert.assertTrue'来自JUnit或TestNG; Java的断言只是'assert'。无论如何,我想这一点只是为了说明问题读者所期望的结果。) – Jonik 2013-04-15 12:26:22

+0

@Jonik Oh , 那就对了。我没有注意。我删除了那一点。 – PapaFreud 2013-04-19 07:54:44

3

通常annonymous用户不需要输入密码,尝试

client.login("anonymous", ""); 
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()); 
    } 
+0

找不到方法:ftpClient.execPBSZ(0); ftpClient.execPROT(“P”) – user3871754 2017-06-30 05:57:15

+0

您是使用FTPClient还是FTPSClient?这些方法只存在于FTPSClient中。 – 2017-06-30 18:24:23

相关问题