龙空技术网

Java SFTP 上传、下载等操作

每日一练Code 229

前言:

现时兄弟们对“sftp java 连接不上”大概比较讲究,咱们都想要知道一些“sftp java 连接不上”的相关内容。那么小编在网上收集了一些对于“sftp java 连接不上””的相关文章,希望兄弟们能喜欢,姐妹们快快来学习一下吧!

Java SFTP 上传、下载等操作

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

JSch是 SSH2 的纯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 (s) {                s;            }            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)) {                s;            }            fileOutputStream = new FileOutputStream(new File(toFilePath));            s(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)) {                s;            }            inputStream = new FileInputStream(new File(localFilePath));            s(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)) {                s;            }            s(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)) {                s;            }            s;            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 = s;        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 官方的文档说明

本文主要用于个人记录笔记!

标签: #sftp java 连接不上