ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java通过sftp模式实现FTP的文件上传下载删除功能

2021-10-10 09:02:27  阅读:155  来源: 互联网

标签:FTP java String 上传下载 param sftp directory import public


项目框架使用springboot, java8, 通过sftp模式实现FTP的文件上传下载删除功能。

1.sftp工具类

package com.example.sftp.utils;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

/**
 *  sftp工具类
 */
@Slf4j
@Component
public class SFTPUtils {

    private ChannelSftp sftp;

    private Session session;

    /**
     * SFTP 登录用户名
     */
    @Value("${sftp.username}")
    private String username;

    /**
     * SFTP 登录密码
     */
    @Value("${sftp.password}")
    private String password;

    /*** 私钥*/
    private String privateKey;

    /**
     * SFTP 服务器地址IP地址
     */
    @Value("${sftp.host}")
    private String host;

    /**
     * SFTP 端口
     */
    @Value("${sftp.port}")
    private int port;


    /**
     * 连接sftp服务器
     */
    public void login() {
        try {
            log.info("connecting...ftp服务器:" + host + ":" + port);
            JSch jsch = new JSch();
            if (privateKey != null) {
                jsch.addIdentity(privateKey);// 设置私钥
            }

            session = jsch.getSession(username, host, port);

            if (password != null) {
                session.setPassword(password);
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);
            session.connect(600000);

            Channel channel = session.openChannel("sftp");
            channel.connect();

            sftp = (ChannelSftp) channel;
            log.info("连接成功...ftp服务器" + host + ":" + port);
        } catch (JSchException e) {
            try {
                Thread.sleep(1000);
                log.info("连接失败...ftp服务器" + host + ":" + port + ":" + e.getMessage(), e);
            } catch (InterruptedException e1) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 关闭连接 server
     */
    public void logout() {
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }


    /**
     * 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
     *
     * @param basePath       服务器的基础路径
     * @param directory      上传到该目录
     * @param sftpFileName   sftp端文件名
     * @param originfilename 本地文件路径
     */
    public void upload(String basePath, String directory, String sftpFileName, String originfilename) throws SftpException, FileNotFoundException {
        try {
            sftp.cd(basePath);
            sftp.cd(directory);
        } catch (SftpException e) {
            //目录不存在,则创建文件夹
            String[] dirs = directory.split("/");
            String tempPath = basePath;
            for (String dir : dirs) {
                if (null == dir || "".equals(dir)) continue;
                tempPath += "/" + dir;
                try {
                    sftp.cd(tempPath);
                } catch (SftpException ex) {
                    sftp.mkdir(tempPath);
                    sftp.cd(tempPath);
                }
            }
        }
        File file = new File(originfilename);
        InputStream is = new FileInputStream(file);
        //上传文件
        sftp.put(is, sftpFileName);
        log.info("上传文件成功:{},源文件:{}", basePath + directory + "/"+ sftpFileName, originfilename);
    }


    /**
     * 下载文件。
     *
     * @param directory    下载目录
     * @param downloadFile 下载的文件
     * @param saveFile     存在本地的路径
     */
    public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
        if (directory != null && !"".equals(directory)) {
            sftp.cd(directory);
        }
        File file = new File(saveFile);
        sftp.get(downloadFile, new FileOutputStream(file));
    }

    /**
     * 下载文件
     *
     * @param directory    下载目录
     * @param downloadFile 下载的文件名
     * @return 字节数组
     */
    public byte[] download(String directory, String downloadFile) throws SftpException, IOException {
        if (directory != null && !"".equals(directory)) {
            sftp.cd(directory);
        }
        InputStream is = sftp.get(downloadFile);
        byte[] fileData = IOUtils.toByteArray(is);
        return fileData;
    }


    /**
     * 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     */
    public void delete(String directory, String deleteFile) throws SftpException {
        sftp.cd(directory);
        sftp.rm(deleteFile);
    }


    /**
     * 列出目录下的文件
     *
     * @param directory 要列出的目录
     */
    public Vector<?> listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }


}

2.配置application.yml的文件服务器信息

sftp:
  host: XX
  port: 22
  username: XX
  password: XX

3.测试类

package com.example.sftp;

import com.example.sftp.utils.SFTPUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SftpUtilsTest {

    @Autowired
    SFTPUtils sftp;

   /**
    * @description 上传
    * @param
    * @return  void
    **/
    @Test
    public void testUpload() throws Exception {
        sftp.login();
        sftp.upload("/data/sftpfile", "/test", "88.pdf", "D:\\tests\\88.pdf");
        sftp.logout();
    }

    /**
     * @description 删除
     * @param
     * @return  void
     **/
    @Test
    public void testDel() throws Exception {
        sftp.login();
        sftp.delete("/data/sftpfile/test", "88.pdf");
        sftp.logout();
    }

    /**
     * @description 下载
     * @param
     * @return  void
     **/
    @Test
    public void testDownload() throws Exception {
        sftp.login();
        sftp.download("/data/sftpfile/test", "88.pdf", "D:\\tests\\89.pdf");
        sftp.logout();
    }


}

4.效果图:

5.下载demo

 https://download.csdn.net/download/weixin_39220472/29983372

标签:FTP,java,String,上传下载,param,sftp,directory,import,public
来源: https://blog.csdn.net/weixin_39220472/article/details/120676903

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有