sftp demo

maven

 		<dependency>
            <groupId>com.jcraftgroupId>
            <artifactId>jschartifactId>
            <version>0.1.54version>
        dependency>

java代码

  • SftpModel 对象
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import lombok.Data;

@Data
public class SftpModel {
    private ChannelSftp sftp;
    private Session session;

}
  • SftpUtils 封装
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.xmpay.third.ftp.model.SftpModel;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SftpUtils {

    /**
     *  连接sftp服务器
     * @param username
     * @param password
     * @param host
     * @param port
     * @return
     * @throws JSchException
     */
    public static SftpModel connect(String username, String password, String host, int port) throws JSchException {
        JSch jsch = new JSch();
        Session 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();

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

        ChannelSftp sftp = (ChannelSftp) channel;
        SftpModel model = new SftpModel();
        model.setSession(session);
        model.setSftp(sftp);
        return model;
    }

    /**
     * 关闭连接
     */
    public static void close(ChannelSftp sftp,Session session) {
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    /**
     * 下载文件 根据上传的目录下载该目录下的所有
     * @param ftpPath下载的文件夹
     * @param localhostPath 本地保存的路径
     * @param prefix 文件名字的前缀
     * @throws SftpException
     */
    public static List<String> downloadFiles(ChannelSftp sftp,String ftpPath, String localPath,String prefix) throws SftpException {
    	List<String> filenames = new ArrayList<>();
        Vector<ChannelSftp.LsEntry> v = sftp.ls(ftpPath);
        if (v != null && !v.isEmpty()) {
            for (int i = 0; i < v.size(); i++) {
                String name = v.get(i).getFilename();
                //文件目录下的每个文件的名字
                if (name.indexOf(".") == 0) {
                    // 过滤掉 . 开头的文件
                } else {
                    //参数1,远程文件地址,参数2,本地目录
                	if(name.startsWith(prefix)) {
                		sftp.get(ftpPath + "/" + name, localPath);
                		filenames.add(localPath + "/" +name);
                	}
                }
            }
        }
        return filenames;
    }

    /**
     *  上传文件
     * @param ftpPath ftp单个文件夹名字
     * @param filename 文件的名字
     * @param input
     * @return 返回图片在sftp上的路径
     */
    public static String upload(ChannelSftp sftp,String ftpPath , String filename,  InputStream input) {
        //InputStream input = new ByteArrayInputStream(bytes);
        // %E9%93%B6%E8%A1%8C%E5%8D%A1%E6%AD%A3%E9%9D%A2.jpg 格式的名字转换为中文
        String decodeName;
        try {
            decodeName = URLDecoder.decode(filename, "utf-8");
            try {
                sftp.cd(ftpPath);
            }catch (Exception e){
                log.error("目录不存在",e);
                sftp.mkdir(ftpPath);
                sftp.cd(ftpPath);
            }
            sftp.put(input,decodeName);
            input.close();
        } catch (Exception io) {
            log.error("文件上传异常",io);
            return null;
        }
        return ftpPath + decodeName;
    }
}

连接获取SftpModel

部分代码

	    SftpModel model;
        try {
            // 连接sftp服务
            model = SftpUtils.connect(ftpUserName, ftpPassword, ftpHost, ftpPort);
        } catch (Exception e) {
            log.error("sftp连接失败", e);
        }

你可能感兴趣的:(ftp)