简体   繁体   中英

Copy directory to a remote machine using SFTP in java

I need to copy a directory from my local machine to a remote machine via SFTP . I've done copying a file through JSCH API , but it doesn't work on directories. Any suggestions?

I'm using the following code:

    JSch jsch = new JSch();
    String filename = localFile.getName();
    com.jcraft.jsch.Session sftpsession = jsch.getSession(username, hostname, 22);
    sftpsession.setUserInfo(new HardcodedUserInfo(password));
    Properties config = new Properties();
    config.setProperty("StrictHostKeyChecking", "no");
    sftpsession.setConfig(config);
    sftpsession.connect();
    ChannelSftp channel = (ChannelSftp)sftpsession.openChannel("sftp");
    channel.connect();
    channel.cd(remoteDirectory);
    channel.put(new FileInputStream(localFile), filename);
    channel.disconnect();
    sftpsession.disconnect();

JSCH doesn't have a single function to recursively send or receive a directory through SFTP. Your code will have to build the list of files and directories to be created on the remote system, then call ChannelSftp.mkdir() and ChannelSftp.put() to create the directories and files.

Also remember that you need to create parent directories before you create subdirectories. For example, mkdir("/foo/bar/baz") will fail if directory /foo/bar doesn't exist.

You can copy folder recursively on remote server using JSCH java API .

Below is the sample code example for the same -

private static void recursiveFolderUpload(String sourcePath, String destinationPath) throws SftpException, FileNotFoundException {

    File sourceFile = new File(sourcePath);
    if (sourceFile.isFile()) {

        // copy if it is a file
        channelSftp.cd(destinationPath);
        if (!sourceFile.getName().startsWith("."))
            channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);

    } else {

        System.out.println("inside else " + sourceFile.getName());
        File[] files = sourceFile.listFiles();

        if (files != null && !sourceFile.getName().startsWith(".")) {

            channelSftp.cd(destinationPath);
            SftpATTRS attrs = null;

            // check if the directory is already existing
            try {
                attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
            } catch (Exception e) {
                System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
            }

            // else create a directory
            if (attrs != null) {
                System.out.println("Directory exists IsDir=" + attrs.isDir());
            } else {
                System.out.println("Creating dir " + sourceFile.getName());
                channelSftp.mkdir(sourceFile.getName());
            }

            for (File f: files) {
                recursiveFolderUpload(f.getAbsolutePath(), destinationPath + "/" + sourceFile.getName());
            }

        }
    }

}

You can refer link here for more details on this code.

You can use this code to copy a directory:

copy(File localFile, String destPath, ChannelSftp clientChannel)
{
    if (localFile.isDirectory()) {
        clientChannel.mkdir(localFile.getName());
        System.out.println("Created Folder: " + localFile.getName() + " in " + destPath);

        destPath = destPath + "/" + localFile.getName();
        clientChannel.cd(destPath);

        for (File file : localFile.listFiles()) {
            copy(file, destPath, clientChannel);
        }

        clientChannel.cd(destPath.substring(0, destPath.lastIndexOf('/')));
    } else {
        System.out.println("Copying File: " + localFile.getName() + " to " + destPath);
        clientChannel.put(new FileInputStream(localFile), localFile.getName(), ChannelSftp.OVERWRITE);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM