Use JSch to put a file to the remote directory and if the directory does not exist, then create it

woraphol.j picture woraphol.j · Oct 11, 2012 · Viewed 33.7k times · Source

I would like to copy a file to the remote directory using Jsch library and SFTP protocol. If the directory on the remote host does not exist, then create it.

In the API doc, http://epaul.github.com/jsch-documentation/javadoc/, I noticed in the put method that there is a kind of "mode" but it is just the transfer mode: - the transfer mode, one of RESUME, APPEND, OVERWRITE.

Is there an easy way to do this without having to write my own code to check the existence and then create a directory recursively?

Answer

Nick Wilson picture Nick Wilson · Oct 11, 2012

Not as far as I know. I use the following code to achieve the same thing:

String[] folders = path.split( "/" );
for ( String folder : folders ) {
    if ( folder.length() > 0 ) {
        try {
            sftp.cd( folder );
        }
        catch ( SftpException e ) {
            sftp.mkdir( folder );
            sftp.cd( folder );
        }
    }
}

where sftp is the ChannelSftp object.