Java realizes cross server upload of files through SFTP

Java realizes cross server upload of files through SFTP

(file upload details)

JSch is short for Java Secure Channel. JSch is a pure java implementation of SSH2. It allows you to connect to an ssh server and can use port forwarding, X11 forwarding, file transfer, etc. of course, you can also integrate its functions into your own applications.
This article only introduces how to use the SFTP function implemented by JSch.
SFTP is the abbreviation of Secure File Transfer Protocol, a Secure File Transfer Protocol. It can provide a secure encryption method for transferring files. SFTP is a part of SSH and a secure way to transfer files to the server. SFTP uses encryption to transmit authentication information and transmitted data, so it is very secure to use SFTP. However, because this transmission mode uses encryption / decryption technology, the transmission efficiency is much lower than that of ordinary FTP. If you have higher requirements for network security, you can use SFTP instead of FTP. (explanation from Baidu)
To use JSch, you need to download its jar package. Please download it from the official website:

ChannelSftp class is the core class for JSch to implement SFTP. It contains all SFTP methods, such as:
put(): file upload
get(): File Download
cd(): enter the specified directory
ls(): get the list of files in the specified directory
rename(): renames the specified file or directory
rm(): deletes the specified file
mkdir(): create directory
rmdir(): delete directory
Etc. (method parameters are omitted here. Both put and get have multiple overloaded methods. Please see the source code for details. They are not listed here.)

JSch supports three file transfer modes:

OVERWRITEFull overwrite mode, which is the default file transfer mode of JSch, that is, if the target file already exists, the transferred file will completely overwrite the target file and generate a new file.
RESUMERecovery mode: if a part of the file has been transferred, the file transfer is interrupted due to the network or any other reason. If the same file is transferred next time, it will be transmitted again from the place where it was interrupted last time.
APPENDAppend mode. If the target file already exists, the transmitted file will be appended after the target file.

Introduced in pom.xml:


Write a tool class to get an SFTP channel object, that is, the instance object of ChannelSftp, according to ip, user name and password. This object can be used in applications to call various operation methods of SFTP.

package com.longyg.sftp;

import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SFTPChannel {
    Session session = null;
    Channel channel = null;

    private static final Logger LOG = Logger.getLogger(SFTPChannel.class.getName());

    public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {

        String ftpHost = sftpDetails.get(SFTPConstants.SFTP_REQ_HOST);
        String port = sftpDetails.get(SFTPConstants.SFTP_REQ_PORT);
        String ftpUserName = sftpDetails.get(SFTPConstants.SFTP_REQ_USERNAME);
        String ftpPassword = sftpDetails.get(SFTPConstants.SFTP_REQ_PASSWORD);

        int ftpPort = SFTPConstants.SFTP_DEFAULT_PORT;
        if (port != null && !port.equals("")) {
            ftpPort = Integer.valueOf(port);

        JSch jsch = new JSch(); // Create JSch object
        session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // Obtain a Session object according to the user name, host ip and port
        LOG.debug("Session created.");
        if (ftpPassword != null) {
            session.setPassword(ftpPassword); // Set password
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // Set the properties for the Session object
        session.setTimeout(timeout); // Set timeout time
        session.connect(); // Link through Session
        LOG.debug("Session connected.");

        LOG.debug("Opening Channel.");
        channel = session.openChannel("sftp"); // Open SFTP channel
        channel.connect(); // Establish connection of SFTP channel
        LOG.debug("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
                + ", returning: " + channel);
        return (ChannelSftp) channel;

    public void closeChannel() throws Exception {
        if (channel != null) {
        if (session != null) {

SFTPConstants is a static member variable class:

package com.longyg.sftp;

public class SFTPConstants {
    public static final String SFTP_REQ_HOST = "host";
    public static final String SFTP_REQ_PORT = "port";
    public static final String SFTP_REQ_USERNAME = "username";
    public static final String SFTP_REQ_PASSWORD = "password";
    public static final int SFTP_DEFAULT_PORT = 22;
    public static final String SFTP_REQ_LOC = "location";

Application example:

package com.longyg.sftp;

import java.util.HashMap;
import java.util.Map;

import com.jcraft.jsch.ChannelSftp;

public class SFTPTest {

    public SFTPChannel getSFTPChannel() {
        return new SFTPChannel();

     * @param args
     * @throws Exception
    public static void main(String[] args) throws Exception {
        SFTPTest test = new SFTPTest();

        Map<String, String> sftpDetails = new HashMap<String, String>();
        // Set host ip, port, user name and password
        sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "");
        sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "root");
        sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "arthur");
        sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "22");
        String src = "D:\\DevSoft\\HB-SnagIt1001.rar"; // Local file name
        String dst = "/home/omc/ylong/sftp/HB-SnagIt1001.rar"; // Destination file name
        SFTPChannel channel = test.getSFTPChannel();
        ChannelSftp chSftp = channel.getChannel(sftpDetails, 60000);
         * Code snippet 1
        OutputStream out = chSftp.put(dst, ChannelSftp.OVERWRITE); // Use OVERWRITE mode
        byte[] buff = new byte[1024 * 256]; // Set the data block size for each transmission to 256KB
        int read;
        if (out != null) {
            System.out.println("Start to read input stream");
            InputStream is = new FileInputStream(src);
            do {
                read =, 0, buff.length);
                if (read > 0) {
                    out.write(buff, 0, read);
            } while (read >= 0);
            System.out.println("input stream read done.");
        chSftp.put(src, dst, ChannelSftp.OVERWRITE); // Code snippet 2
        // chSftp.put(new FileInputStream(src), dst, ChannelSftp.OVERWRITE); //  Code snippet 3

Note: Please uncomment code segment 1, code segment 2 and code segment 3 respectively and run the program for testing. These three pieces of code demonstrate how to upload files using different put methods of JSch.

Code snippet 1: transfer the file by writing data to the output stream returned by the put method. It is up to the program to decide what data to write. Here, the input stream of the local file is written to the output stream. The advantage of this method is that you can set the size of the data block written to the output stream each time, such as the statement in this example:

byte[] buff = new byte[1024 * 256]; // Set the data block size for each transmission to 256KB

Code snippet 2: directly upload the local file named src to the target server, and the target file name is dst. (Note: when using this method, dst can be a directory. When dst is a directory, the uploaded target file name will be the same as src file name)

Code snippet 3: upload the file input stream with the local file name src to the target server, and the target file name is dst.

The functions of these three codes are the same. They upload the local file src to the server's dst file. You can choose which implementation method to use according to the specific situation.

Original link: 36795183 / article / details / 786215

Tags: Java ssh

Posted on Mon, 27 Sep 2021 07:17:02 -0400 by markmh84