【问题标题】:java.lang.NullPointerException Downloading file from FTP with listFiles methodjava.lang.NullPointerException 使用 listFiles 方法从 FTP 下载文件
【发布时间】:2014-02-24 11:14:26
【问题描述】:

我想获取 ftp 上存在的所有文件名,扩展名为 .xls。

因此我编写了以下代码:

FTPClient ftp = new FTPClient();
FTPFile[] downloadFiles = null;
try {
    ftp.connect(Ftp_Path);
    ftp.login(ftpUserID, ftpPassword);

    downloadFiles = ftp.listFiles();

    xlsFiles = new ArrayList<String>();
    for(FTPFile i : downloadFiles) {
       if(i.toString().endsWith(".xls")) {
           xlsFiles.add(i.toString());
       }
    }

} catch (Exception e) {
    e.printStackTrace();
}

我已确定文件存在于 ftp 上:

但是在线出错:

downloadFiles = ftp.listFiles();

我遵循以下语法:

http://kodejava.org/how-do-i-get-list-of-files-from-ftp-server/

但出现错误:

java.lang.NullPointerException
    at com.amazonaws.mws.samples.ImportRulesPropertyClass.GetFileList(ImportRulesPropertyClass.java:39)
    at com.amazonaws.mws.samples.ManageReportScheduleSample.main(ManageReportScheduleSample.java:74)

【问题讨论】:

  • 首先检查你的 ftp.connect(Ftp_Path); ftp.login(ftpUserID, ftpPassword); ftp 连接与否?
  • 你在哪里初始化ftp?
  • @Naren 是的,它已连接,我在每个地方都保留了调试器
  • @Alexander_Winter 以上下载文件为:FTPClient ftp = new FTPClient();
  • @NaMo 它正在使用相同的代码...。代码在哪个函数中?? ImportRulesPropertyClass.GetFileList 是什么??

标签: java ftp


【解决方案1】:

用户在代码下方获取文件列表

FTPClient f=FTPClient();
    f.connect(server);
    f.login(username, password);
    FTPListParseEngine engine = f.initiateListParsing(directory);

    while (engine.hasNext()) {
       FTPFile[] files = engine.getNext(25);  // "page size" you want
       //do whatever you want with these files, display them, etc.
       //expensive FTPFile objects not created until needed.
    }

【讨论】:

    【解决方案2】:

    我补充说:

    ftp.enterLocalPassiveMode();
    

    在之前的代码中:

    String downloadFiles[]=ftp.listNames("");
    

    它现在可以工作了

    【讨论】:

    • enterLocalPassiveMode 如果您通过 NAT 路由器运行客户端或者您对服务器的可见性有限,则需要。这是影响某些 FTP 命令(如 LIST、PUT、GET)的特殊情况,这些命令会打开在某些网络中被阻止的第二个 TCP 通道。
    • @Dubas thanx,我意识到了...对 java 来说是全新的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多