ftp - FtpSession.exist(path) 不适用于文件
问题描述
我正在尝试使用 Spring Integration 检查 FTP 服务器中文件的存在,但它似乎不起作用。它适用于目录但不适用于文件。在文档中提到适用于目录和文件。我是否正确构建路径?
private DefaultFtpSessionFactory getFTPFactory() {
DefaultFtpSessionFactory defaultFtpSessionFactory = new DefaultFtpSessionFactory();
defaultFtpSessionFactory.setHost("localhost");
defaultFtpSessionFactory.setPort(21);
defaultFtpSessionFactory.setUsername("foo");
defaultFtpSessionFactory.setPassword("pass");
return defaultFtpSessionFactory;
}
public boolean getFTPFiles() throws IOException {
DefaultFtpSessionFactory defaultFtpSessionFactory = getFTPFactory();
FtpSession ftpSession = defaultFtpSessionFactory.getSession();
FTPClient clientInstance = ftpSession.getClientInstance();
clientInstance.enterLocalPassiveMode();
return ftpSession.exists("/ftp/foo/study/download/test_1.txt");
}
解决方案
我们不知道您的路径是否正确。里面的逻辑FtpSession.exists()
是这样的:
public boolean exists(String path) throws IOException {
Assert.hasText(path, "'path' must not be empty");
String[] names = this.client.listNames(path);
boolean exists = !ObjectUtils.isEmpty(names);
if (!exists) {
String currentWorkingPath = this.client.printWorkingDirectory();
Assert.state(currentWorkingPath != null,
"working directory cannot be determined; exists check can not be completed");
try {
exists = this.client.changeWorkingDirectory(path);
}
finally {
this.client.changeWorkingDirectory(currentWorkingPath);
}
}
return exists;
}
因此,它尝试在用户工作目录中列出提供的路径。如果不是,它会尝试将工作目录切换到提供的路径,这显然不适用于文件名......
我可以建议尝试使用FtpRemoteFileTemplate.exists()
. 查看它的 JavaDocs:
/**
* This particular FTP implementation is based on the {@link FTPClient#getStatus(String)}
* by default, but since not all FTP servers properly implement the {@code STAT} command,
* the framework internal {@link FtpRemoteFileTemplate} instances are switched to the
* {@link FTPClient#listNames(String)} for only files operations.
* <p> The mode can be switched with the {@link #setExistsMode(ExistsMode)} property.
* <p> Any custom implementation can be done in an extension of the {@link FtpRemoteFileTemplate}.
* @param path the remote file path to check.
* @return true or false if remote file exists or not.
*/
@Override
public boolean exists(final String path) {
我不确定localPassive/ActiveMode
...
也许有一种方法可以调查服务器日志以确定为什么它不允许您查看该文件的问题?
推荐阅读
- android - 片段中的 setHasOptionsMenu 导致内存泄漏
- python - 如果每个元素都被屏蔽,如何让 np.ma.argmin 返回 None?
- nginx - 如何设置位置块以从 url 中剥离端口
- c# - AJAX 调用适用于 GET 但不适用于 POST
- python - Python 在 For 循环中创建新变量
- powershell - 无法将变量插入到 Get-Item 的路径中
- python - Python - Statsmodels - 不同的输入类型会导致不同的输出类型?
- python - 为什么我的 Flask Python 网页上的提交按钮重定向到同一个 HTML 模板,而不是另一个模板?
- regex - 从长文本中提取字符串以用作搜索键
- python - 使用 .join() 和列表推导将前缀连接到列表中的每个单词