打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java SFTP 上传、下载等操作

实际开发中用到了 SFTP 用于交换批量数据文件,然后琢磨了下这方面的东西,基于 JSch 写了个工具类记录下,便于日后使用。

JSchSSH2 的纯Java实现。JSch 可以连接到sshd服务器并使用端口转发,X11转发,文件传输等,并且很方便的将其功能集成到Java程序中。

1、添加依赖

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

2、SFTPUtils 工具类

public class SFTPUtils {
    private Logger log = LoggerFactory.getLogger(SFTPUtils.class);

    private String host; // 主机名称/IP
    private int port = 22; // 端口
    private String username; // 用户名
    private String password; // 密码

    private ChannelSftp sftp = null;
    private Channel channel = null;
    private Session session = null;

    public SFTPUtils(String host, String userName, String password) {
        this.host = host;
        this.username = userName;
        this.password = password;
    }

    public SFTPUtils(String host, int port, String userName, String password) {
        this.host = host;
        this.port = port;
        this.username = userName;
        this.password = password;
    }

    /**
     * 连接SFTP服务器
     *
     * @throws JSchException
     */
    public void connect() throws JSchException {
        JSch jSch = new JSch();
        session = jSch.getSession(username, host, port);
        session.setPassword(password);
        session.setConfig(this.buildConfig());
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
        sftp = (ChannelSftp) channel;
        log.info("连接主机:{} 登录成功", host);
    }

    /**
     * 构建连接配置参数
     *
     * @return Properties
     */
    private Properties buildConfig() {
        Properties properties = new Properties();
        properties.put("StrictHostKeyChecking", "no");
        return properties;
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        try {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
            if (channel.isConnected()) {
                channel.disconnect();
            }
            if (session.isConnected()) {
                session.disconnect();
            }
        } catch (Throwable e) {
            //ignore
        }
    }

    /**
     * 下载文件
     *
     * @param sftpPath   服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
     *                   例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
     *                   指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
     * @param fileName   文件名
     * @param toFilePath 下载保存文件路径,路径+文件名,例如:d:/test.txt
     * @return
     */
    public boolean downloadFile(String sftpPath, String fileName, String toFilePath) {
        FileOutputStream fileOutputStream = null;
        try {
            if (StringUtils.isNotBlank(sftpPath)) {
                sftp.cd(sftpPath);
            }
            fileOutputStream = new FileOutputStream(new File(toFilePath));
            sftp.get(fileName, fileOutputStream);
            return true;
        } catch (Exception e) {
            log.error("下载文件错误", e);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
        return false;
    }

    /**
     * 上传文件
     *
     * @param sftpPath      服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
     *                      例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
     *                      指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
     * @param fileName      上传后文件名
     * @param localFilePath 文件路径,路径+文件名,例如:d:/test.txt
     * @return
     */
    public boolean uploadFile(String sftpPath, String fileName, String localFilePath) {
        FileInputStream inputStream = null;
        try {
            if (StringUtils.isNotBlank(sftpPath)) {
                sftp.cd(sftpPath);
            }
            inputStream = new FileInputStream(new File(localFilePath));
            sftp.put(inputStream, fileName);
            return true;
        } catch (Exception e) {
            log.error("上传文件错误", e);
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
        return false;
    }

    /**
     * 上传文件
     *
     * @param sftpPath    服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
     *                    例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
     *                    指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
     * @param fileName    上传后文件名
     * @param inputStream 文件输入流
     * @return
     */
    public boolean uploadFile(String sftpPath, String fileName, InputStream inputStream) {
        try {
            if (StringUtils.isNotBlank(sftpPath)) {
                sftp.cd(sftpPath);
            }
            sftp.put(inputStream, fileName);
            return true;
        } catch (Exception e) {
            log.error("上传文件错误", e);
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
        return false;
    }

    /**
     * 删除文件
     *
     * @param sftpPath 服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
     *                 例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
     *                 指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
     * @param fileName 文件名
     * @return
     */
    public boolean deleteFile(String sftpPath, String fileName) {
        try {
            if (StringUtils.isNotBlank(sftpPath)) {
                sftp.cd(sftpPath);
            }
            sftp.rm(fileName);
            return true;
        } catch (Exception e) {
            log.error("删除文件失败", e);
        }
        return false;
    }

    /**
     * 查询指定目录下信息
     *
     * @param sftpPath 服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
     *                 例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
     *                 指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
     * @return
     */
    public List<String> listFiles(String sftpPath) throws SftpException {
        Vector files = sftp.ls(sftpPath);
        List<String> result = new ArrayList<String>();
        Iterator iterator = files.iterator();
        while (iterator.hasNext()) {
            LsEntry isEntity = (LsEntry) iterator.next();
            result.add(isEntity.getFilename());
        }
        return result;
    }
}

在使用的的时候,需要调用 connect()开启连接,使用完后调用 disconnect() 关闭连接 。

jsch

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
不保存直接读取压缩流内二级目录下的文件内容
详解sftp实现对远程服务器的文件操作
JAVA程序实现对SFTP服务器的操作,无密码
九种方式,教你读取 resources 目录下的文件路径
struts实现文件下载
struts2 文件下载示例1_普通下载
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服