Instructions for using JSch to connect Sftp


Recently, I need to pass SSH Then on SFTP Connect, and then operate, so record here, convenient for future use, also convenient for everyone as a reference.


First of all, you need to make a dependency reference to JSch, and the project is built by gradle.
Here is the build.gradle Code:

compile group: 'com.jcraft', name: 'jsch', version: '0.1.54'

Then we need an entity class to configure the relevant parameters of our JSch.
Tips: the company uses AWS, and the parameters are all configured in ECS. So I need to take the corresponding value from the environment variable. You can change it to hard code.
Entity class:

public class SftpConfigProperties {

    public static final String environment=System.getenv("PUBLISHER_ENVIRONMENT");

    public static final String sftpUsername=System.getenv("PUBLISHER_SFTP_USERNAME");

    public static final String sftpHost=System.getenv("PUBLISHER_SFTP_HOST");

    public static final int sftpPort=Integer.valueOf(System.getenv("PUBLISHER_SFTP_PORT"));

    public static final String sftpPassword=System.getenv("PUBLISHER_SFTP_PASSWORD");

    public static final String sftpFilePath="/"+environment+"/dir_publisher_sftp";

Finally, the most important is the main class of jsch:
The code is as follows:

package com.harry.jsch;

import com.jcraft.jsch.*;
import com.kingland.dst.config.SftpConfigProperties;
import org.apache.log4j.Logger;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

 * this method is used to connect to sftp with jsch
public class SftpConnectUtil {
    private  static Logger logger=Logger.getLogger(SftpConnectUtil.class);

     * This method is used to connect to sftp
     * @param ip
     * @param user
     * @param password
     * @param port
     * @return session
    public  Session connect(String ip,String user,String password,int port){"start to connect to sftp");
        Session session=null;
        JSch jsch=new JSch();
        try {
            //Give the user name, ip address and port number required for connection
            session=jsch.getSession(user, ip, port);
            //When you log in for the first time, do you need a prompt? value can be filled in yes, no or ask
            session.setConfig("StrictHostKeyChecking", "no");
           //Set whether to time out
           //Set password
            //Create connection
  "sftp session set properties success");
        } catch (JSchException e) {
        if(session == null) {
            logger.error("session is null");
        }else if(session.isConnected() == true) {
  "connet to sftp server is successful");
        return session;

     * This method is used to upload files
     * @param session
     * @param filePath
     * @param fileName
    public  void uploadFile(Session session,String filePath,String fileName) {
        ChannelSftp channel =null;
        String filePathName=filePath+File.separator+fileName;
        FileInputStream fis =null;
        try {
            fis = new FileInputStream(new File(filePathName));
            // To create a connection, sftp
            channel =(ChannelSftp)session.openChannel("sftp");
            channel.put(fis, fileName);
        } catch (JSchException e) {
        } catch (SftpException e) {
        } catch (FileNotFoundException e1) {
        } catch (IOException e) {
    //This method is used to delete the corresponding files on sftp
    //The ls method is used to extract all the file names under the specified folder
    //After traversal, get the file name for deletion. Before deletion, give judgment conditions or make the file name
    public void deleteExpireFile(ChannelSftp channel){
        for(Object obj:vector){
            if(obj instanceof ChannelSftp.LsEntry){
                String fileName=((ChannelSftp.LsEntry) obj).getFilename();
                if (".".equals(fileName) || "..".equals(fileName)) {
      "success delete the file :"+SftpConfigProperties.sftpFilePath+File.separator+fileName);


Thank you for watching. I hope it can help you

Tags: Java Session sftp Gradle

Posted on Fri, 13 Dec 2019 12:41:36 -0500 by jrmckee