【问题标题】:Check if file exists using Apache Commons VFS2使用 Apache Commons VFS2 检查文件是否存在
【发布时间】:2015-08-30 23:01:43
【问题描述】:

我想问一下是否有办法只使用 Apache Commons 来检查文件夹中是否已经存在文件。

我有上传到 SFTP 文件夹的方法,但只要该方法运行,它就会覆盖当前文件。该方法设置为每 5 分钟运行一次。我需要一个代码来创建 if 语句来检查文件是否已经不在 SFTP 位置,如果没有,则执行我的复制方法,如果有文件,则跳过它。

我的复制方法是这样的

private void copyFileSFTP(File model, String hour) throws IOException {
    StandardFileSystemManager manager = new StandardFileSystemManager();
    String dest = String.format("%s/%s/model/%s", destinationPath, hour,
            model.getName());

    remoteDirectory = String.format("%s/%s/model/", destinationPath, hour);

    try {
        if (!model.exists())
            LOG.error("Error. Local file not found");

        // Initializes the file manager
        manager.init();

        // Setup our SFTP configuration
        FileSystemOptions opts = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                opts, "no");
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts,
                false);
        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

        // Create the SFTP URI using the host name, userid, password, remote
        // path and file name
        String sftpUri = "sftp://" + userId + ":" + password + "@"
                + serverAddress + "/" + remoteDirectory + model.getName();

        **HERE I NEED THE CHECK IF THE MODEL EXISTS ALREADY ON SFTP**

        // Create local file object
        FileObject localFile = manager.resolveFile(model.getAbsolutePath());

        // Create remote file object
        FileObject remoteFile = manager.resolveFile(sftpUri, opts);

        // Copy local file to sftp server
        remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
        LOG.info("File upload successful");
        LOG.info("New file has been created.");
        LOG.info(dest);

    } catch (Exception ex) {
        LOG.error(ex);
        handleBadPath(model, hour);

    } finally {
        manager.close();
    }

}

感谢您的帮助。

【问题讨论】:

标签: java file sftp apache-commons-vfs


【解决方案1】:

【讨论】:

  • 那么stackoverflow.com/questions/21399561/… 第四部分最终会起作用吗?
  • 对不起,我的意思是该链接中的第二个:检查远程主机位置中是否存在文件
  • 是的,除了它们根本不使用.exists()的返回值。
  • 他们使用检查可能是为了验证上传是否成功,而不是为了防止覆盖。
猜你喜欢
  • 1970-01-01
  • 2015-08-05
  • 2019-04-10
  • 2021-08-28
  • 2020-02-09
  • 2011-06-26
  • 2012-07-19
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多