0

I am using Apache Commons VFS2 to upload a file to server. Below is the code for the same. I have all the credentials right. The code printed "File uploaded successfully" String as well. But, I could not find the file on server when i cross checked it. Is there anything i am missing here in the code ?

I have all the Jars required (Apache Commons VFS jars, JSH jar)

public static void main(String[] args) {

    SendMyFiles sendMyFiles = new SendMyFiles();

    sendMyFiles.startFTP("C:/useragent.log");

}

public boolean startFTP(String fileToFTP) {

    props = new Properties();
    StandardFileSystemManager manager = new StandardFileSystemManager();

    try {

        // props.load(new FileInputStream("properties/" +
        // propertiesFilename));
        String serverAddress = "10.111.111.11";
        String userId = "username";
        String password = "password";
        String remoteDirectory = "local/home/client/files/";

        // check if the file exists
        String filepath = fileToFTP;
        File file = new File(filepath);
        if (!file.exists())
            throw new RuntimeException("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, true);
        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;

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

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

        // Copy local file to sftp server
        remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
        System.out.println("File upload successful");

    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    } finally {
        manager.close();
    }

    return true;
}
BIndu_Madhav
  • 577
  • 1
  • 8
  • 21

1 Answers1

1

I'd assume that the sftpUri should be a path to the destination file, not directory:

String sftpUri =
    "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory + "/" +
    file.getName(); 
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992