使用 Apache Commons VFS2 检查文件是否存在



我想问一下是否有办法仅使用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();
    }
}

谢谢你的帮助。

使用FileObject.exists()方法。

见 https://commons.apache.org/proper/commons-vfs/commons-vfs2/apidocs/org/apache/commons/vfs2/FileObject.html#exists--

相关内容

  • 没有找到相关文章