Sftp in java

By | July 18, 2015
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Below code can download/upload from/to sftp server:

package ftp;

import com.jcraft.jsch.*;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.*;
import java.util.Vector;


/**
 * Created by pli on 7/16/2015.
 */
@Data
public class SftpService {

    private static Logger logger = LoggerFactory.getLogger(SftpService.class);

    private String host;
    private String username;
    private String password;

    public void downloadFilesFromSftp(String sftpFromDir, String downloadFileName, String toLocalDir) {
        JSch jSch = new JSch();
        Session session = null;
        Channel channel = null;
        try {

            session = jSch.getSession(username, host, 22);
            session.setPassword(password);

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            config.put("PreferredAuthentications", "publickey,password");
            session.setConfig(config);
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();

            ChannelSftp channelSftp;
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(sftpFromDir);
            Vector<ChannelSftp.LsEntry> list = channelSftp.ls(downloadFileName);
            for(ChannelSftp.LsEntry entry : list) {
                try {
                    Path filePath;
                    filePath = Paths.get(toLocalDir +  "/" + entry.getFilename());
                    Files.copy(channelSftp.get(sftpFromDir + "/" + entry.getFilename()), filePath, StandardCopyOption.REPLACE_EXISTING);
                }catch (IOException e){
                    logger.error("Encountered error when dealing with " + entry.getFilename() + ":" + e.toString());
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        finally {
            if(channel != null ){
                channel.disconnect();
            }
            if(session != null){
                session.disconnect();
            }
        }
    }

    public void uploadFilesFromSftp(String localFromDir, String uploadFileName, String toSftpDir)  {
        JSch jSch = new JSch();
        Session session = null;
        Channel channel = null;
        try {

            session = jSch.getSession(username, host, 22);
            session.setPassword(password);

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            config.put("PreferredAuthentications", "publickey,password");
            session.setConfig(config);
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();

            ChannelSftp channelSftp;
            channelSftp = (ChannelSftp) channel;
            DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get(localFromDir), uploadFileName);
            for (Path localFileFrom : ds) {
                try {
                    channelSftp.put(new FileInputStream(new File(localFileFrom.toString())), toSftpDir + "/" + localFileFrom.getFileName());
                }catch (IOException e){
                    logger.error("Encountered error when dealing with " + localFileFrom.toString() + ":" + e.toString());
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        finally {
            if(channel != null ){
                channel.disconnect();
            }
            if(session != null){
                session.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        SftpService sftpServiceDownload = new SftpService();
        sftpServiceDownload.setHost("hostname");
        sftpServiceDownload.setUsername("username");
        sftpServiceDownload.setPassword("password");
        sftpServiceDownload.downloadFilesFromSftp("/home", "*.txt", "/home");


        SftpService sftpServiceUpload = new SftpService();
        sftpServiceUpload.setHost("hostname");
        sftpServiceUpload.setUsername("username");
        sftpServiceUpload.setPassword("password!ake");
        sftpServiceUpload.uploadFilesFromSftp("/home", "*", "/root");
    }

}

pom dependency:

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-sftp</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>