Java中通过sftp协议获取指定目录文件列表

在Java中,你可以使用第三方库,如JSch,来实现SFTP协议并获取指定目录的文件列表。
JSch是Java Secure Channel的缩写,是一个java实现的可以完成sftp上传下载的工具,我们可以集成它的功能到自己的应用程序,本文介绍使用JSch实现的SFTP上传下载的功能。ChannelSftp类是JSch实现SFTP核心类,它包含了所有SFTP的方法,如
在这里插入图片描述

实例:使用JSch库获取SFTP服务器上指定目录的文件列表。
首先,确保你的项目中包含了JSch库。如果你使用Maven,可以添加以下依赖:

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

然后,使用以下Java代码来获取指定目录的文件列表:

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
 
import java.util.Vector;
 
public class SFTPExample {
    public static void main(String[] args) {
        String host = "192.168.100.100";
        int port = 22;
        String user = "username";
        String password = "password";
        String remoteDir = "/path/to/directory";
 
        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;
 
        try {
            // Setup JSch session.
            session = jsch.getSession(user, host, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();
 
            // Open SFTP channel.
            channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;
 
            // Change to the target directory.
            sftpChannel.cd(remoteDir);
 
            // Get the file list for the current directory.
            Vector<ChannelSftp.LsEntry> list = sftpChannel.ls("*");
 
            for (ChannelSftp.LsEntry entry : list) {
                System.out.println(entry.getFilename());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close the channel and the session.
            if (sftpChannel != null) {
                sftpChannel.exit();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}

上述代码中,我们首先建立了一个SFTP通道并连接,然后改变到指定的远程目录,并使用通配符*获取该目录下的所有文件和文件夹列表。之后,我们遍历这个列表并打印出文件名。最后,在操作完成后,关闭了通道和会话,释放资源。

SFTP工具类示例如下

import com.jcraft.jsch.*;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.*;

public class SftpClientUtil {
    private static Logger logger = Logger.getLogger(SftpClientUtil.class);
    private Session session;
    private Channel channel;
    private ChannelSftp sftp;
    private InputStream in;
    private OutputStream out;

    /**
     * 构造函数1
     *
     * @param host       主机
     * @param username   用户名
     * @param password   密码
     * @param port       端口
     * @param isHightSSH :jsch 与 ssh 版本适配,ssh>7.6 为true,反之为false
     * @throws Exception
     */
    public SftpClientUtil(String host, String username, String password, int port, boolean isHightSSH) throws Exception {
        JSch jsch = new JSch();
        this.session = jsch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
        if (isHightSSH) {
            config.put("kex", "diffie-hellman-group1-sha1,"
                    + "diffie-hellman-group-exchange-sha1,"
                    + "diffie-hellman-group-exchange-sha256"); //适配新版本ssh需添加对应的加密算法
        }
        session.setConfig(config);
        try {
            session.connect();
        } catch (Exception e) {
            if (session.isConnected())
                session.disconnect();
            logger.error("链接报错!!!", e);
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        channel = session.openChannel("sftp");
        try {
            if (channel.isConnected())
                channel.disconnect();
            channel.connect();
        } catch (Exception e) {
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        sftp = (ChannelSftp) channel;
    }

    /**
     * 构造函数2
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @param encoding 字符集编码
     * @throws Exception
     */
    public SftpClientUtil(String host, String username, String password, int port, String encoding) throws Exception {
        JSch jsch = new JSch();
        this.session = jsch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
        session.setConfig(config);
        try {
            session.connect();
        } catch (Exception e) {
            if (session.isConnected())
                session.disconnect();
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        channel = session.openChannel("sftp");
        try {
            channel.connect();
        } catch (Exception e) {
            if (channel.isConnected())
                channel.disconnect();
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        sftp = (ChannelSftp) channel;
        sftp.setFilenameEncoding(encoding);
    }

    /**
     * 构造函数3
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @param encoding 字符集
     * @param timeout  超时时间
     * @throws Exception
     */
    private SftpClientUtil(String host, String username, String password, int port, String encoding, int timeout)
            throws Exception {
        JSch jsch = new JSch();
        this.session = jsch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
        session.setConfig(config);
        try {
            session.connect();
        } catch (Exception e) {
            if (session.isConnected())
                session.disconnect();
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        session.setTimeout(timeout);
        channel = session.openChannel("sftp");
        try {
            channel.connect();
        } catch (Exception e) {
            if (channel.isConnected())
                channel.disconnect();
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        sftp = (ChannelSftp) channel;
        sftp.setFilenameEncoding(encoding);
    }

    /**
     * 文件上传
     *
     * @param remotePath     远端路径
     * @param remoteFileName 上传到远端后的文件名
     * @param localPath      本地路径
     * @param localFileName  本地文件名
     * @return
     */
    public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        FileInputStream in = null;
        try {
            createDir(remotePath);
            File file = new File(localPath + localFileName);
            in = new FileInputStream(file);
            sftp.put(in, remoteFileName);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    //创建目录
    public boolean createDir(String createpath) {
        try {
            createpath = createpath.trim();
            if (isDirExist(createpath)) {
                this.sftp.cd(createpath);
                logger.info("cd " + createpath);
                return true;
            }
            String[] pathArray = createpath.split("/");
            for (String path : pathArray) {
                path = path.trim();
                if ("".equals(path)) {
                    continue;
                }
                if (!isDirExist(path)) {
                    sftp.mkdir(path);
                }
                logger.info("cd " + path);
                sftp.cd(path);
            }
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }

    //判断目录是否存在
    public boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                logger.error("directory:" + directory + ",no such file ERROR!!!");
            }
        }
        return isDirExistFlag;
    }

    /**
     * 文件下载
     *
     * @param remotePath    远程文件存放路径
     * @param localPath     下载到本地的路径
     * @return 下载后的文件名集合
     * @throws Exception
     */
    public List<String> downloadFiles(String remotePath, String localPath){
        List<String> downloadFiles = new ArrayList<String>();

        try {
            logger.info("切换到指定目录:" + remotePath);
            boolean flag = openDir(remotePath, sftp);
            if (flag) {
                //1.获取远端路径下所有文件
                Vector<?> vv = listFiles("*");
                if (vv == null) {
                    return null;
                } else {
                    for (Object object : vv) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        String remoteFileName = entry.getFilename();

                        logger.info("校验文件名:" + remoteFileName);
                        String path = localPath.substring(localPath.length() - 1).equals("/") ? localPath : localPath + "/";
                        File file = new File(path + remoteFileName);
                        logger.info("保存校对文件的本地路径为:" + file.getAbsolutePath());

                        logger.info("start downLoad " + remoteFileName + " ~~");
                        sftp.get(remoteFileName, new FileOutputStream(file));
                        logger.info("downLoad ok ~~");

                        downloadFiles.add(remoteFileName);
                    }

                    if (downloadFiles.size() < 1) {
                        logger.error("remotePath:" + remotePath + "路径下,未匹配到校对文件!");
                    }
                }
            } else {
                logger.info("对应的目录" + remotePath + "不存在!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                }
            }
            if (session != null) {
                if (session.isConnected()) {
                    session.disconnect();
                }
            }
        }
        return downloadFiles;
    }

    //打开或者进入指定目录
    public boolean openDir(String directory, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            logger.info("cd " + directory + " ok");
            return true;
        } catch (SftpException e) {
            logger.error(e + "");
            return false;
        }
    }

    //返回目录下所有文件信息
    public Vector listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }

    /**
     * 断开与主机的连接
     */
    public void disconnect() {
        try {
            sftp.disconnect();
        } catch (Exception ignored) {
        }
        try {
            channel.disconnect();
        } catch (Exception ignored) {
        }
        try {
            session.disconnect();
        } catch (Exception ignored) {
        }
    }

    /**
     * 得到SFTP实例
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @return
     * @throws Exception
     */
    public static SftpClientUtil getInstans(String host, String username, String password, int port) throws Exception {
        return new SftpClientUtil(host, username, password, port, false);
    }

    /**
     * 得到SFTP实例
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @param encoding 字符集编码
     * @return
     * @throws Exception
     */
    public static SftpClientUtil getInstans(String host, String username, String password, int port, String encoding)
            throws Exception {
        return new SftpClientUtil(host, username, password, port, encoding);
    }

    /**
     * 得到SFTP实例
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @param encoding 字符集编码
     * @param timeout  超时时间
     * @return
     * @throws Exception
     */
    public static SftpClientUtil getInstans(String host, String username, String password, int port, String encoding,
                                            int timeout) throws Exception {
        return new SftpClientUtil(host, username, password, port, encoding, timeout);
    }
}
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值