Check if file exists using Apache Commons VFS2

3.9k views Asked by At

I would like to ask if there is a way how to check if file already exists in the folder using only Apache Commons.

I have method which uploads into the SFTP folder but it overwrites current files anytime the method is running. The method is set to run every 5 minutes. I need a code which will create and if statement which checks if the file is not at the SFTP location already and then, if not executes my copy method, if there is a file, then skips it.

My copy method looks like this

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();
    }

}

Thank you for help.

1

There are 1 answers

4
Martin Prikryl On BEST ANSWER