从sftp下载多个文件

时间:2013-12-29 10:54:19

标签: java sftp

我正在使用以下代码从SFTP服务器“ara22122013.txt”下载此文件:

我想下载服务器中包含字符串22122013,

的所有文件

这里的例子:

 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);
        }
}

请告知如何?

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码。我希望这会对你有所帮助。

 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();
    }
}
}

答案 1 :(得分:0)

您可以使用以下代码段:

Vector path = channelSftp.ls("C:/SFTP/" );

for(String s : path){
channelSftp.get(s, "C:/SFTP/" );
}

请查看channelSftp.ls()