Reputation: 221
I am downloading this file from an SFTP server "ara22122013.txt", using the below code:
I want to download all the files in the server that has the string 22122013,
Here' example:
Sring SFTPHOST = "10.10.10.10";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
JSch jsch = new JSch();
public void test()
{
try {
session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
System.out.println("Checking username, host, and port...");
session.setPassword(SFTPPASS);
System.out.println("Checking password...");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Session Connected");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("Channel Connected");
channelSftp = (ChannelSftp)channel;
try {
channelSftp.get("ara22122013.txt", "C:/SFTP/" );
} catch (SftpException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (JSchException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
Please advise how?
Upvotes: 1
Views: 2922
Reputation: 985
You can use following code. I hope this will help you.
import java.nio.channels.Channel;
import java.util.Vector;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SFTPJava {
/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String SFTPHOST = "10.20.30.40";
int SFTPPORT = 22;
String SFTPUSER = "USERNAME";
String SFTPPASS = "PASSWORD";
String SFTPWORKINGDIR = "/home/data/";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
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();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
Vector filelist = channelSftp.ls(SFTPWORKINGDIR);
for (int i = 0; i < filelist.size(); i++) {
System.out.println(filelist.get(i).toString());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Upvotes: 2
Reputation: 4899
You can use the following snippet:
Vector path = channelSftp.ls("C:/SFTP/" );
for(String s : path){
channelSftp.get(s, "C:/SFTP/" );
}
Please have a look to channelSftp.ls().
Upvotes: 0