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

时间:2015-06-15 12:35:34

标签: java file sftp apache-commons-vfs

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

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)