<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
package com.wit.tsp.member.util;
import com.jcraft.jsch.*;
import com.wit.tsp.member.config.OneLinkConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.util.Properties;
import java.util.Vector;
/**
* @author hankongbin
* @date 2022/4/20 11:45
*/
@Slf4j
@Component
public class SftpUtil {
@Resource
private OneLinkConfig oneLinkConfig;
private static OneLinkConfig.Sftp sftpConfig;
@PostConstruct
public void init() {
sftpConfig = oneLinkConfig.getSftp();
// ChannelSftp sftp = login();
// try {
// upload(sftp, String.format(sftpConfig.getDirectory(), "11", "requestId2"), new File("D:\\result.txt"));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (SftpException e) {
// e.printStackTrace();
// }
}
/**
* 连接sftp服务器
*/
public ChannelSftp login() {
String host = sftpConfig.getHost();
int port = sftpConfig.getPort();
JSch jsch = new JSch();
log.info("sftp connect... host:{} port:{}", host, port);
try {
Session session = jsch.getSession(sftpConfig.getUsername(), host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(sftpConfig.getPassword());
Properties config = new Properties();
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
log.info("sftp server host:{}, port:{} is connect successFull!", host, port);
return (ChannelSftp) channel;
} catch (JSchException e) {
log.error("connect failed!host:{}, port:{}", host, port, e);
}
return null;
}
/**
* 关闭连接 server
*/
public void logout(ChannelSftp channelSftp) {
if (channelSftp != null) {
if (channelSftp.isConnected()) {
channelSftp.disconnect();
log.info("sftp is closed already");
}
try {
Session session = channelSftp.getSession();
if (session.isConnected()) {
session.disconnect();
log.info("sshSession is closed already");
}
} catch (JSchException e) {
log.info("sftp is closed failed", e);
}
}
}
/**
* 将输入流的数据上传到sftp作为文件
*
* @param directory 上传到该目录
* @param sftpFileName sftp端文件名
* @param input 输入流
* @throws SftpException
* @throws Exception
*/
public void upload(ChannelSftp channel, String directory, String sftpFileName, InputStream input) throws SftpException {
try {
channel.cd(directory);
} catch (SftpException e) {
log.warn("directory is not exist");
// 创建文件夹
channel.mkdir(directory);
channel.cd(directory);
}
channel.put(input, sftpFileName);
log.info("file:{} is upload successful", sftpFileName);
}
/**
* 上传单个文件
*
* @param directory 上传到sftp目录
* @throws FileNotFoundException
* @throws SftpException
*/
public void upload(ChannelSftp channel, String directory, File file) throws FileNotFoundException, SftpException {
upload(channel, directory, file.getName(), new FileInputStream(file));
}
/**
* 将byte[]上传到sftp,作为文件。注意:从String生成byte[]是,要指定字符集。
*
* @param directory 上传到sftp目录
* @param sftpFileName 文件在sftp端的命名
* @param byteArr 要上传的字节数组
* @throws SftpException
*/
public void upload(ChannelSftp channel, String directory, String sftpFileName, byte[] byteArr) throws SftpException {
upload(channel, directory, sftpFileName, new ByteArrayInputStream(byteArr));
}
/**
* 将字符串按照指定的字符编码上传到sftp
*
* @param directory 上传到sftp目录
* @param sftpFileName 文件在sftp端的命名
* @param dataStr 待上传的数据
* @param charsetName sftp上的文件,按该字符编码保存
* @throws UnsupportedEncodingException
* @throws SftpException
*/
public void upload(ChannelSftp channel, String directory, String sftpFileName, String dataStr, String charsetName) throws UnsupportedEncodingException, SftpException {
upload(channel, directory, sftpFileName, new ByteArrayInputStream(dataStr.getBytes(charsetName)));
}
/**
* 下载文件
*
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
* @throws SftpException
* @throws FileNotFoundException
*/
public void download(ChannelSftp channel, String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
if (directory != null && !"".equals(directory)) {
channel.cd(directory);
}
File file = new File(saveFile);
channel.get(downloadFile, new FileOutputStream(file));
log.info("file:{} is download successful", downloadFile);
}
/**
* 下载文件
*
* @param directory 下载目录
* @param downloadFile 下载的文件名
* @return 字节数组
* @throws SftpException
* @throws IOException
*/
public byte[] download(ChannelSftp channel, String directory, String downloadFile) throws SftpException, IOException {
if (directory != null && !"".equals(directory)) {
channel.cd(directory);
}
InputStream is = channel.get(downloadFile);
byte[] fileData = IOUtils.toByteArray(is);
log.info("file:{} is download successful", downloadFile);
return fileData;
}
/**
* 删除文件
*
* @param directory 要删除文件所在目录
* @param deleteFile 要删除的文件
* @throws SftpException
*/
public void delete(ChannelSftp channel, String directory, String deleteFile) throws SftpException {
channel.cd(directory);
channel.rm(deleteFile);
}
/**
* 列出目录下的文件
*
* @param directory 要列出的目录
* @param channel
* @return
* @throws SftpException
*/
public Vector<?> listFiles(ChannelSftp channel, String directory) throws SftpException {
return channel.ls(directory);
}
/**
* 判断文件大小
*
* @param file 文件
* @param size 限制大小
* @param unit 限制单位(B,K,M,G)
* @return
*/
public static boolean checkFileSize(File file, int size, String unit) {
long len = file.length();
double fileSize = 0;
if ("B".equals(unit.toUpperCase())) {
fileSize = (double) len;
} else if ("K".equals(unit.toUpperCase())) {
fileSize = (double) len / 1024;
} else if ("M".equals(unit.toUpperCase())) {
fileSize = (double) len / 1048576;
} else if ("G".equals(unit.toUpperCase())) {
fileSize = (double) len / 1073741824;
}
if (fileSize > size) {
return false;
}
return true;
}
}