首页 > 解决方案 > 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");
  }

标签: ftpspring-integrationspring-integration-ftp

解决方案


我们不知道您的路径是否正确。里面的逻辑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...

也许有一种方法可以调查服务器日志以确定为什么它不允许您查看该文件的问题?


推荐阅读