Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 643
woraphol.j Avatar asked Oct 11 '12 11:10

woraphol.j


People also ask

What is JSch?

JSch is a pure Java implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.

What is ChannelSftp?

public class ChannelSftp extends Channel. A Channel connected to an sftp server (as a subsystem of the ssh server). This class supports the client side of the sftp protocol, version 3, and implements an interface similar to the usual sftp command line client.

How do I use SFTP in Java?

You can use SFTP to connect via SSH to your Java application and then transfer files. With SFTP, you connect using SSH and then transfer files with SFTP. To do this, you can use the JSch (Java secure channel) library.


1 Answers

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.

like image 118
Nick Wilson Avatar answered Sep 20 '22 14:09

Nick Wilson