SFTP 帮助类

package com.tms.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.tms.entity.oinv.Sftp;

public class WppSftpDownloadUtil {

	private static final Log log = LogFactory.getLog(WppSftpDownloadUtil.class);
	
	private static ChannelSftp channelSftp;
	private static Session session;
	
	public static boolean connectSftp(Sftp sftp) throws Exception {
		
		try {
			// 校验参数
			validConnectParam(sftp);
			
			JSch jsch = new JSch();
			log.info("connect host[" + sftp.getHost() + "] port[" + sftp.getPort() + "] userName[" + sftp.getUserName() + "]");

			session = jsch.getSession(sftp.getUserName(), sftp.getHost(), sftp.getPort());
			
			String password = sftp.getPassword();
			if (password != null) {
                session.setPassword(password);
                log.info("sftp connect password[" +password+ "]");
            }
			Properties config = new Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.setTimeout(1000*30);
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            log.info("channel is connected");
            
            channelSftp = (ChannelSftp) channel;

            return true;
		} catch (Exception e) {
			log.error("connect SFTP failed==>" + e.getMessage(), e);
			throw e;
		}
		
	}
	
	// 校验参数
	private static void validConnectParam(Sftp sftp) throws Exception {
		if (sftp == null) {
			throw new Exception("FTP can not be null.");
		}
		if (StringUtils.isEmpty(sftp.getHost())) {
			throw new Exception("SFTP host can not be null.");
		}
		if (StringUtils.isEmpty(sftp.getUserName())) {
			throw new Exception("SFTP userName can not be null.");
		}
	}
	
	/**
	 * 关闭SFTP连接
	 */
	public static void closeSftp() {
		if (channelSftp != null) {
			if (channelSftp.isConnected()) {
				channelSftp.disconnect();
				log.info("channelSftp is closed already");
			}
		}
		if (session != null) {
			if (session.isConnected()) {
				session.disconnect();
				log.info("sshSession is closed already");
			}
		}
	}
	
	/**
	 * 
	 * @param directory sftp 文件夹路径
	 * @param srcFile  sftp文件夹下的文件
	 * @param distFilePath 
	 * @throws Exception
	 */
	public static void downloadFile(String directory, String srcFile, String distFilePath,String  backupsFile) throws Exception {
		log.info("download file==>" + directory + File.separator + srcFile);
		//进入sftp文件夹
		channelSftp.cd(channelSftp.getHome());
		channelSftp.cd(directory);  
		channelSftp.get(srcFile, distFilePath);
		copyFile(distFilePath, backupsFile);
		new File(distFilePath).delete();
		log.info("file[" + srcFile + "] download successful...");
	}
	
	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					log.info("bytesum ==> " + bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
				log.info("[COPY_FILE:" + oldfile.getPath() + "复制文件成功!]");
			}
		} catch (Exception e) {
			log.error("复制单个文件操作出错",e);
		}
	}
	
	
	public static List<String> getDirFiles(String directory) throws Exception {
		List<String> fileNameList = new ArrayList<>();
		Vector<LsEntry> v = channelSftp.ls(directory);
		for (int i = 0; i < v.size(); i++) {
			String name = v.get(i).getFilename();
			log.info("name:" + name);
			if (".".equals(name) || "..".equals(name)) {
				continue;
			}
			fileNameList.add(name);
		}
		return fileNameList;
	}
	
	public static void delete(String directory, String deleteFile) throws Exception {
		channelSftp.cd("..");
		channelSftp.cd(directory);
		channelSftp.rm(deleteFile);
		log.info("删除文件成功!===》"+directory+File.separator+deleteFile);
	}
	
	/**
	 * 上传文件到sftp目录
	 * @param directory SFTP端目录
	 * @param sftpFileName 文件名
	 * @param input 上传文件流
	 * @throws Exception
	 */
	public static void uploadFile(String directory, String sftpFileName, InputStream input) throws Exception {
		try {
			channelSftp.cd(directory);
		} catch (Exception e) {
			// 如果sftp对应文件夹不存在则创建
			log.info("directory[" + directory + "] is not exist, create...");
			channelSftp.mkdir(directory);
			channelSftp.cd(directory);
		}
		channelSftp.put(input, sftpFileName);
		log.info("file[" + sftpFileName + "] upload successful...");
	}
	
	/**
	 * 上传文件到sftp目录
	 * @param directory SFTP端目录
	 * @param uploadFile 上传文件
	 * @throws Exception
	 */
	public static void uploadFile(String directory, String uploadFile) throws Exception {
		File file = new File(uploadFile);
		log.info("uploadFile==>" + uploadFile);
		if (!file.exists()) {
			throw new Exception("文件[" + uploadFile + "]不存在");
		}
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			channelSftp.cd(channelSftp.getHome());
//			channelSftp.cd(directory);
			uploadFile(directory, file.getName(), fis);
		} catch (Exception e) {
			throw e;
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
	}
	
	/**
	 * 上传文件到sftp目录
	 * @param directory SFTP端目录
	 * @param sftpFileName 文件名称
	 * @param dataStr 待上传的数据
	 * @param charsetName sftp上的文件,按该字符编码保存
	 * @throws Exception
	 */
	public void uploadFile(String directory, String sftpFileName, String dataStr, String charsetName) throws Exception { 
		ByteArrayInputStream bais = null;
		try {
			bais = new ByteArrayInputStream(dataStr.getBytes(charsetName));
			uploadFile(directory, sftpFileName, bais);  
		} catch (Exception e) {
			throw e;
		} finally {
			if (bais != null) {
				bais.close();
			}
		}
    }

	public static Sftp assembleSftpTest() throws Exception {
		Sftp sftp = new Sftp("用户名", "密码", "IP地址", 端口);
		return sftp;
	}
	
	// TODO 组装SFTP连接对象
	public static Sftp assembleSftp() throws Exception {
		Sftp sftp = null;
		
		
		return sftp;
	}
}

 实体类

package com.tms.entity.oinv;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.tms.annotation.ColumnAlias;

@Entity
@Table(name="TAXIC_SFTP")
public class Sftp {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id", unique = true, nullable = false, precision = 20, scale = 0)
	private Long id;
	
	@ColumnAlias("SFTP配置类型") /*1: wpp销项    2:fvm财务本地化*/
	@Column(name = "type", length = 1, nullable = false)
	private String type;
	
	@ColumnAlias("FTP 登录用户名")
	@Column(name = "userName", length = 100, nullable = false)
	private String userName;
	
	@ColumnAlias("FTP 登录密码")
	@Column(name = "password", length = 100, nullable = false)
	private String password;

	@ColumnAlias("私钥路径")
	@Column(name = "privateKey", length = 100, nullable = false)
	private String privateKey;

	@ColumnAlias("FTP 服务器地址IP地址")
	@Column(name = "host", length = 100, nullable = false)
	private String host;

	@ColumnAlias("FTP 端口")
	@Column(name = "port", length = 100, nullable = false)
	private int port;
	
 

	@ColumnAlias("FTP回写文件夹  路径")
	@Column(name = "incoming", length = 1000, nullable = false)
	private String incoming; 
	
	@ColumnAlias("FTP导入文件夹 路径")
	@Column(name = "outgoing ", length = 1000, nullable = false)
	private String outgoing ; 
	
	@ColumnAlias("本地 fpt下载的系统 路径")
	@Column(name = "locaDownloadDirectory", length = 1000, nullable = false)
	private String locaDownloadDirectory;
	
	
	@ColumnAlias("本地 fpt下载文件的备份路径")
	@Column(name = "locaDownloadBackupsDirectory", length = 1000, nullable = false)
	private String locaDownloadBackupsDirectory;
	
	
	@ColumnAlias("本地 fpt上传的系统 路径")
	@Column(name = "locaUploadDirectory", length = 1000, nullable = false)
	private String locaUploadDirectory;
	
	@ColumnAlias("本地 fpt上传文件的备份路径")
	@Column(name = "locaUploadBackupsDirectory", length = 1000, nullable = false)
	private String locaUploadBackupsDirectory;
	
	@ColumnAlias("销项文件上传模板")
	@Column(name = "outputUploadEemplate", length = 1000, nullable = false)
	private String outputUploadEemplate;
	
	
	
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPrivateKey() {
		return privateKey;
	}

	public void setPrivateKey(String privateKey) {
		this.privateKey = privateKey;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	
	
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}


 
	
 

	public String getIncoming() {
		return incoming;
	}

	public void setIncoming(String incoming) {
		this.incoming = incoming;
	}

	public String getOutgoing() {
		return outgoing;
	}

	public void setOutgoing(String outgoing) {
		this.outgoing = outgoing;
	}

	public String getLocaDownloadDirectory() {
		return locaDownloadDirectory;
	}

	public void setLocaDownloadDirectory(String locaDownloadDirectory) {
		this.locaDownloadDirectory = locaDownloadDirectory;
	}

	public String getLocaDownloadBackupsDirectory() {
		return locaDownloadBackupsDirectory;
	}

	public void setLocaDownloadBackupsDirectory(String locaDownloadBackupsDirectory) {
		this.locaDownloadBackupsDirectory = locaDownloadBackupsDirectory;
	}

	public String getLocaUploadDirectory() {
		return locaUploadDirectory;
	}

	public void setLocaUploadDirectory(String locaUploadDirectory) {
		this.locaUploadDirectory = locaUploadDirectory;
	}

	public String getLocaUploadBackupsDirectory() {
		return locaUploadBackupsDirectory;
	}

	public void setLocaUploadBackupsDirectory(String locaUploadBackupsDirectory) {
		this.locaUploadBackupsDirectory = locaUploadBackupsDirectory;
	}
	
	

	public String getOutputUploadEemplate() {
		return outputUploadEemplate;
	}

	public void setOutputUploadEemplate(String outputUploadEemplate) {
		this.outputUploadEemplate = outputUploadEemplate;
	}

	
	
	
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Sftp() {
	}

	/**
	 * 构造基于密码认证的sftp对象
	 * @param userName
	 * @param password
	 * @param host
	 * @param port
	 */
	public Sftp(String userName, String password, String host, int port) {
		this.userName = userName;
		this.password = password;
		this.host = host;
		this.port = port;
	}

	/**
	 * 构造基于秘钥认证的sftp对象
	 * @param userName
	 * @param host
	 * @param port
	 * @param privateKey
	 */
	public Sftp(String userName, String host, int port, String privateKey) {
		this.userName = userName;
		this.host = host;
		this.port = port;
		this.privateKey = privateKey;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值