【问题标题】:When downloading a listed file using Apache Common Net FTPClient the downloaded file is empty or the returned InputStream is null使用 Apache Common Net FTPClient 下载列出的文件时,下载的文件为空或返回的 InputStream 为空
【发布时间】:2019-09-10 05:55:24
【问题描述】:

我正在为我的 FTP 客户端项目使用 Apache Commons Net FTP 库。我成功登录,但当我尝试从 FTP 服务器下载文件时,得到了空文件或 null InputStream

我尝试设置文件传输模式或文件类型,但都不起作用。

这是我启动客户端的代码示例:

FTPClient client = new FTPClient();
client.connect(host, port);
client.login(user, password);

这是检索文件的代码:

// I do some filtering here, only download file containing certain prefix/suffix/text
FTPFile[] file = client.listFiles(fullDirectory, (file) -> file != null && file.isFile() && file.getName().contains(fileName));
// get the real file
// this will produce file with empty content
client.retrieveFile(file.getName(), new FileOutputStream(new File(file.getName))); 

// get InputStream
// this will produce null InputStream
InputStream is = client.retrieveFileStream(file.getName()); 

我还尝试添加一些其他属性,例如:

FTPClient client = new FTPClient();
client.connect(host, port);
client.setFileType(FTP.ASCII_FILE_TYPE);
client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
client.login(user, password);

但它们都不起作用。

这可能与服务器配置有关吗?实际上我没有对 FTP 服务器的配置访问权限。提供者只给了我对它的读取权限。

【问题讨论】:

  • 谢谢@MartinPrikryl 我已经添加了日志,当执行RETR {file name} 时它显示消息550 Failed to open file。这是因为权限问题吗?
  • 您可以使用任何(GUI)FTP 客户端下载文件吗?
  • 是的,我可以使用 FileZilla 下载文件。

标签: java ftp apache-commons-net


【解决方案1】:

您正在列出一个特定目录 (fullDirectory)。但是,您正在从当前工作目录下载文件(未指定完整路径)。所以可能找不到。

尝试将目录路径与文件名结合起来:

fullDirectory + "/" + file.getName()

您可能正在寻找这个:
Download entire FTP directory in Java (Apache Net Commons)

【讨论】:

  • 谢谢马丁!刚刚意识到我没有检索到完整目录的文件。现在可以了!
  • 完成!再次感谢马丁。
猜你喜欢
  • 2016-06-11
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2019-11-14
  • 2011-03-09
  • 2020-02-12
相关资源
最近更新 更多