JAVA-SFTP上传文件

话不多说,先上代码。使用guice注入。其他使用自行修改
`
import com.google.inject.Singleton;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

/**
* Created by darkangel on 2017/2/23.
*/
@Singleton
public class BMKPSFtpUtil {
private static final Logger log = LoggerFactory.getLogger(BMKPSFtpUtil.class);

private static final String CHARSET = "UTF-8";

/**
 * 打开session通道
 * @param ip  主机IP
 * @param user 主机登陆用户名
 * @param psw 主机登陆密码
 * @param port 主机ssh2登陆端口,如果取默认值,传-1
 * @return
 */
public Session openSession(String ip,int port, String user, String psw){
    JSch jsch = new JSch();
    Session session = null;
    try {
        // 采用指定的端口连接服务器
        session = jsch.getSession(user, ip, port);


        // 如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }

        // 设置登陆主机的密码
        session.setPassword(psw);// 设置密码

        // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties

        // 设置登陆超时时间
        session.setTimeout(30000);
        session.connect();
    }catch (JSchException ex1){
        log.error("sftp 上传失败:jsch创建session失败");
    }catch (Exception ex2){
        log.error("sftp 上传失败:session为null无法连接");
    }
    return session;
}

/**
 * 获取SFTP管道(sftp)
 * @param session
 * @param type  连接类型:TYPE:exec 、 sftp
 * @return <T> T
 */
public ChannelSftp getChannelSftp(Session session, String type){
    ChannelSftp channel = null;
    try {
        // 创建sftp通信通道
        channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return channel;
}

/**
 * 关闭session,关闭SFTP连接
 * @param sftp
 * @throws Exception
 */
public void closeChannel(Channel sftp, Session session) throws Exception {
    if (sftp != null) {
        if (sftp.isConnected()) {
            sftp.disconnect();
        }
    }
    if (session != null) {
        if (session.isConnected()) {
            session.disconnect();
        }
    }
}

/**
 * SFTP上传图片方法 上传文件存放目录:根目录/data/images/工程名/yyyyMMdd/
 * 备注:为了提高连接可用性,统一在执行批量操作后调用closeChannel关闭连接
 * @param channelSftp
 * @param uploadFile  目标文件名
 * @param target   远程目标目录
 * @throws Exception
 */
public void upload(ChannelSftp channelSftp,String uploadFile,String target) {
    File file = new File(uploadFile);
    try {
        channelSftp.cd(target); // 切换到指定目录
        channelSftp.put(new FileInputStream(file), file.getName());//上传文件
    } catch (SftpException ex1) {
        log.error("sftp 上传失败:打开远程目录");
    }catch (FileNotFoundException ex2){
        log.error("sftp 上传失败:文件不存在 ");
    }
}

}
`

使用

ChannelSftp channel = null; //sftp管道声明
        Session session = null;  //session声明
        try {
            //1.建立sftp连接
            session = sftpUtil.openSession(IP,PORT, USERNAME, PASSWORD);
            channel = sftpUtil.getChannelSftp(session,"sftp");  //获取管道符

            //2.上传原图片到资源服务器临时目录下
            File file = new File(PIC_PATH);
            sftpUtil.upload(channel,PIC_PATH,TMP_STORE_PATH);

            //3.mv到远程正式文件夹
            sftpUtil.excCommand(session,"mv -f -u "+TMP_STORE_PATH+file.getName()+" "+STORE_PATH+file.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            sftpUtil.closeChannel(channel,session);
        }
        return null;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值