title: Downloading Multiple Files via SFTP using Java
body: <p>I am new to java and I am trying to write a script that will pull multiple files from various SFTP sites daily.</p>
  
  <p>I have code below that will pull 1 file from 1 site and it works,  however I am struggling to find how to modify my code so that it will download multiple files.  So for example all the files in the remote directory, or only certain files containing certain letters</p>
  
  <p>Can you advise me on this please?</p>
  
  <p>code:-</p>
  
  <pre><code>package package1;  
  
  import java.io.BufferedInputStream;  
  import java.io.BufferedOutputStream;  
  import java.io.File;  
  import java.io.FileOutputStream;  
  import java.io.OutputStream;  
  import com.jcraft.jsch.Channel;  
  import com.jcraft.jsch.ChannelSftp;  
  import com.jcraft.jsch.JSch;  
  import com.jcraft.jsch.Session;  
  
  
  
  public class SFTPpullsshkeys {  
  public SFTPpullsshkeys() {  
                            }
  
  public static void main(String[] args) {  
          String SFTPHOST = "IP";  
          int    SFTPPORT = 22;  
          String SFTPUSER = "Username";  
          String passphrase = "passphrase";  
          String SFTPWORKINGDIR = "remote directory";    
          String prikeyfile = "C:\\Open SSH Key.ppk";
  
  
          Session     session     = null;  
          Channel     channel     = null;  
          ChannelSftp channelSftp = null;  
  
  try{  
          JSch jsch = new JSch();  
          jsch.addIdentity(prikeyfile, passphrase);
          session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);  
          session.setConfig("StrictHostKeyChecking", "no"); 
          session.connect();  
          channel = session.openChannel("sftp");  
          channel.connect();  
          channelSftp = (ChannelSftp)channel;  
          channelSftp.cd(SFTPWORKINGDIR);  
          byte[] buffer = new byte[1024];  
          BufferedInputStream bis = new BufferedInputStream(channelSftp.get("file.csv"));  
          File newFile = new File("C:\\file.csv"); 
          OutputStream os = new FileOutputStream(newFile);  
          BufferedOutputStream bos = new BufferedOutputStream(os);  
          int readCount;  
  
  while
          ( (readCount = bis.read(buffer)) &gt; 0) {  
          System.out.println("Writing files to disk: " );  
          bos.write(buffer, 0, readCount);  
          }  
          bis.close();  
          bos.close();  
          }catch(Exception ex){  
          ex.printStackTrace();  
  
          }  
  
      }      
  
  } 
  </code></pre>