Search code examples
javasftpjschprivate-key

downloading all files from sftp server in java


I am trying to Download All files from folder on SFTP server , Below is my Code Please suggest changes so i can download All available files from remote directory and can save to Local Directory

package svb.ftp.bs.load;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.FileNotFoundException;
import java.io.File;
import java.io.FileInputStream;

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

import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import java.util.List;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.io.IOUtils;

import org.junit.Test;

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

import java.io.IOException;
import java.io.InputStream;

import java.util.Vector;

public class downloadFtp {

    public static void main(String[] args) {

        String SFTPHOST = "host";
        int SFTPPORT = 22;
        String SFTPUSER = "user";
        String SFTPPASS = "Pass";
        String privateKey = "E:\\Oracle\\mywork\\DownloadFTP\\ppk.ppk";
        String SFTPWORKINGDIR = "Inbox/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT";

        com.jcraft.jsch.Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        JSch jsch = new JSch();
        try {
            jsch.addIdentity(privateKey);
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("Connected");
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);

            
            InputStream is = channelSftp.get(SFTPWORKINGDIR);
            IOUtils.copy(is, System.out);
            is.close();


            System.out.println("File Uploaded to FTP Server Sucessfully.");
        } catch (JSchException jse) {
            // TODO: Add catch code
            jse.printStackTrace();
        } catch (SftpException se) {
            // TODO: Add catch code
            se.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
       

    }
}

Currently when i run the code it show below error

4: Can't change directory: /Inbox/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT
    at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:350)
    at svb.ftp.bs.load.downloadFtp.main(downloadFtp.java:67)
Process exited with exit code 0.

Solution

  • The stacktrace is telling you what's wrong.

    Can't change directory: /Inbox/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT

    Problem is with:

    channelSftp.cd(SFTPWORKINGDIR);
    

    Here you are passing filename but its expecting a directory (cd stands for Change Directory). You cannot do CD to a file.

    If you pass a folder/path it would work. Try the following :

    channelSftp.cd("/Inbox/a_folder/");
    

    How to Download All: Reference: https://ganeshtiwaridotcomdotnp.blogspot.com/2020/07/download-files-from-ftp-using-jsch-java.html

    In order to download all files, first list all files in root folder, iterate over it.. if its a file download, if its a folder list the content and keep doing it recursively for sub folders.

    The following is an example of how to download files from a defined folder:

    import com.jcraft.jsch.*;
    
    import java.util.Properties;
    import java.util.Vector;
    
    public class JschDownload {
    
        public static void main(String[] args) {
    
            Session session = null;
            Channel channel = null;
            JSch jsch = new JSch();
            try {
                session = jsch.getSession("demo", "test.rebex.net", 22);
                session.setPassword("password");
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                System.out.println("session connect");
    
    
                channel = session.openChannel("sftp");
                channel.connect();
                System.out.println("Connected");
    
                ChannelSftp channelSftp = (ChannelSftp) channel;
                downloadFromFolder(channelSftp, "/");
                downloadFromFolder(channelSftp, "/pub/example/");
    
                System.out.println("File Uploaded to FTP Server Sucessfully.");
            } catch (Exception e) {
                e.printStackTrace();
    
            } finally {
                if (channel != null) {
                    channel.disconnect();
                }
                session.disconnect();
            }
    
        }
    
        static void downloadFromFolder(ChannelSftp channelSftp, String folder) throws SftpException {
            Vector<ChannelSftp.LsEntry> entries = channelSftp.ls(folder);
            System.out.println(entries);
    
            //download all from root folder
            for (ChannelSftp.LsEntry en : entries) {
                if (en.getFilename().equals(".") || en.getFilename().equals("..") || en.getAttrs().isDir()) {
                    continue;
                }
    
                System.out.println(en.getFilename());
                channelSftp.get(folder + en.getFilename(), en.getFilename());
            }
        }
    
    }
    

    Refer to http://www.jcraft.com/jsch/examples/ for examples and documentation of the jsch library.