修订记录 |
版本 |
是否发布 |
2020-08-03 |
v1.0 |
是 |
一、SFTP工具类
import com.*.*.common.util.FileUtil;
import com.*.*.common.util.StringUtil;
import com.google.common.collect.Lists;
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.SftpATTRS;
import com.jcraft.jsch.SftpException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.lang3.StringUtils;
public class SftpTools {
private Session session;
private Channel channel;
private ChannelSftp chnSftp;
private static final int FILE_TYPE = 1;
private static final int DIR_TYPE = 2;
private final SftpBean sftpBean;
public SftpTools(SftpBean sftpBean) {
this.sftpBean = sftpBean;
}
public static void main(String[] args) throws IOException, SftpException, JSchException {
SftpBean sftpBean = new SftpBean();
sftpBean.setUserName("sftp");
sftpBean.setSecretKey("superlop123456");
sftpBean.setHost("10.60.69.184");
sftpBean.setPort(22);
sftpBean.setSftpPath("/inbox/emft");
sftpBean.setSftpBackupPath("/inbox/backup");
String fileName = "SOLBI_00MPF_20200713_20200717092327_MPF.xlsx";
SftpTools sftpTools = new SftpTools(sftpBean);
sftpTools.open();
sftpTools.moveFile(sftpBean.getSftpPath() + File.separator + fileName, sftpBean.getSftpBackupPath(), "fail");
sftpTools.close();
}
public void open() throws JSchException {
this.connect();
}
private void connect() throws JSchException {
if (StringUtils.isBlank(sftpBean.getPrivateKey()) && StringUtils.isBlank(sftpBean.getSecretKey())) {
String tempPrivateKeyPath = System.getProperty("user.home") + File.separator + ".ssh" + File.separator + "id_rsa";
if (FileUtil.isExisted(tempPrivateKeyPath)) {
sftpBean.setPrivateKey(tempPrivateKeyPath);
}
}
JSch jsch = new JSch();
if (StringUtils.isNotBlank(sftpBean.getPrivateKey())) {
jsch.addIdentity(sftpBean.getPrivateKey());
}
session = jsch.getSession(sftpBean.getUserName(), sftpBean.getHost(), sftpBean.getPort());
session.setPassword(sftpBean.getSecretKey());
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect(20000);
channel = session.openChannel("sftp");
channel.connect();
chnSftp = (ChannelSftp) channel;
}
private void cd(String sftpPath) throws SftpException {
chnSftp.cd(sftpPath);
}
private String pwd() throws SftpException {
return chnSftp.pwd();
}
public List<String> listFiles(String directory, int fileType) throws SftpException {
List<String> fileList = Lists.newArrayList();
if (isDirExist(directory)) {
boolean itExist;
Vector<?> vector;
vector = chnSftp.ls(directory);
for (Object obj : vector) {
String str = obj.toString().trim();
int tag = str.lastIndexOf(":") + 3;
String strName = str.substring(tag).trim();
itExist = isDirExist(directory + File.separator + strName);
if (fileType == FILE_TYPE) {
if (!(itExist)) {
fileList.add(directory + File.separator + strName);
}
}
if (fileType == DIR_TYPE) {
if (itExist) {
if (!(strName.equals(".") || strName.equals(".."))) {
fileList.add(directory + File.separator + strName);
}
}
}
}
}
return fileList;
}
private boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = chnSftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
public InputStream getFile(String sftpFilePath) throws SftpException {
if (isFileExist(sftpFilePath)) {
return chnSftp.get(sftpFilePath);
}
return null;
}
public InputStream getInputStreamFile(String sftpFilePath) throws SftpException {
return getFile(sftpFilePath);
}
public ByteArrayInputStream getByteArrayInputStreamFile(String sftpFilePath) throws SftpException, IOException {
if (isFileExist(sftpFilePath)) {
byte[] srcFtpFileByte = inputStreamToByte(getFile(sftpFilePath));
ByteArrayInputStream srcFtpFileStreams = new ByteArrayInputStream(srcFtpFileByte);
return srcFtpFileStreams;
}
return null;
}
public String delFile(String sftpFilePath) throws SftpException {
String retInfo;
if (isFileExist(sftpFilePath)) {
chnSftp.rm(sftpFilePath);
retInfo = "1:File deleted.";
} else {
retInfo = "2:Delete file error,file not exist.";
}
return retInfo;
}
public void moveFile(String srcSftpFilePath, String distSftpFilePath, String fileNameTag)
throws SftpException, IOException {
boolean dirExist;
boolean fileExist;
fileExist = isFileExist(srcSftpFilePath);
dirExist = isDirExist(distSftpFilePath);
if (!fileExist) {
return;
}
if (!(dirExist)) {
createDir(distSftpFilePath);
}
String fileName = srcSftpFilePath.substring(srcSftpFilePath.lastIndexOf(File.separator));
ByteArrayInputStream srcFtpFileStreams = getByteArrayInputStreamFile(srcSftpFilePath);
if (StringUtil.isNotBlank(fileNameTag)) {
fileName = String.format("%s.%s", fileName, fileNameTag);
}
this.chnSftp.put(srcFtpFileStreams, distSftpFilePath + fileName);
this.chnSftp.rm(srcSftpFilePath);
}
public void copyFile(String srcSftpFilePath, String distSftpFilePath) throws SftpException, IOException {
boolean dirExist;
boolean fileExist;
fileExist = isFileExist(srcSftpFilePath);
dirExist = isDirExist(distSftpFilePath);
if (!fileExist) {
return;
}
if (!(dirExist)) {
createDir(distSftpFilePath);
}
String fileName = srcSftpFilePath
.substring(srcSftpFilePath.lastIndexOf(File.separator));
ByteArrayInputStream srcFtpFileStreams = getByteArrayInputStreamFile(srcSftpFilePath);
this.chnSftp.put(srcFtpFileStreams, distSftpFilePath + fileName);
}
public void createDir(String sftpDirPath) throws SftpException {
this.cd(File.separator);
if (this.isDirExist(sftpDirPath)) {
return;
}
String[] pathStr = sftpDirPath.split(File.separator);
for (String path : pathStr) {
if (path.equals("")) {
continue;
}
if (isDirExist(path)) {
this.cd(path);
} else {
this.chnSftp.mkdir(path);
this.chnSftp.cd(path);
}
}
this.cd(File.separator);
}
public boolean isFileExist(String srcSftpFilePath) {
boolean isExitFlag = false;
if (getFileSize(srcSftpFilePath) >= 0) {
isExitFlag = true;
}
return isExitFlag;
}
public long getFileSize(String srcSftpFilePath) {
long fileSize;
try {
SftpATTRS sftpATTRS = chnSftp.lstat(srcSftpFilePath);
fileSize = sftpATTRS.getSize();
} catch (Exception e) {
fileSize = -1;
if (e.getMessage().toLowerCase().equals("no such file")) {
fileSize = -2;
}
}
return fileSize;
}
public void close() {
if (channel.isConnected()) {
channel.disconnect();
}
if (session.isConnected()) {
session.disconnect();
}
}
public byte[] inputStreamToByte(InputStream inputStream) throws IOException {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = inputStream.read()) != -1) {
bytestream.write(ch);
}
byte[] imgData = bytestream.toByteArray();
bytestream.close();
return imgData;
}
}
二、配置文件Bean
import com.*.toolset.BcToolSet;
import java.util.Objects;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public class SftpBean {
@NotBlank(message = "userNamecan not be null")
private String userName;
private String secretKey;
@NotBlank(message = "host not be null")
private String host;
@NotNull(message = "port not be null")
private int port;
private String privateKey;
@NotBlank(message = "sftpPath not be null")
private String sftpPath;
private String sftpBackupPath;
public SftpBean() {
}
public SftpBean(String userName, String secretKey, String host, int port, String privateKey) {
super();
this.userName = userName;
this.secretKey = secretKey;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String password) {
this.secretKey = password;
}
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 String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public String getSftpPath() {
return sftpPath;
}
public void setSftpPath(String sftpPath) {
this.sftpPath = sftpPath;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || BcToolSet.getClass(this) != BcToolSet.getClass(o)) {
return false;
}
SftpBean sftpBean = (SftpBean) o;
return port == sftpBean.port &&
userName.equals(sftpBean.userName) &&
secretKey.equals(sftpBean.secretKey) &&
host.equals(sftpBean.host) &&
privateKey.equals(sftpBean.privateKey) &&
sftpPath.equals(sftpBean.sftpPath);
}
@Override
public int hashCode() {
return Objects.hash(userName, secretKey, host, port, privateKey, sftpPath);
}
public String getSftpBackupPath() {
return this.sftpBackupPath;
}
public void setSftpBackupPath(String sftpBackupPath) {
this.sftpBackupPath = sftpBackupPath;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南