所依赖maven
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
具体工具类代码
package com.dmc.loan.assist.core.common.infra.util.ftp;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
/**
* @author lw
* @date 2023/11/29 11:32
*/
@Slf4j
public class SftpUtils {
private static ChannelSftp sftp;
private SftpUtils() {
}
private static class SingletonHolder{
private static final SftpUtils INSTANCE = new SftpUtils();
}
/**
* 懒汉式单例
*
*/
public static SftpUtils getInstance() {
return SingletonHolder.INSTANCE;
}
/**
* 连接sftp服务器
*
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
*/
public void connect(String host, int port, String username, String password) {
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
log.info("SFTP Session connected.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
log.info("Connected to " + host);
} catch (Exception e) {
log.error(e.getMessage());
}
sftp = channelSftp;
}
/**
* 下载文件
*
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
*/
public File download(String directory, String downloadFile, String saveFile) {
try {
sftp.cd(directory);
Path path = Paths.get(saveFile);
if (!Files.exists(path)) {
Files.createDirectories(path.getParent());
Files.createFile(path);
}
File file = new File(saveFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftp.get(downloadFile, fileOutputStream);
fileOutputStream.close();
return file;
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}
/**
* 断开连接
*/
public void disconnect() {
try {
sftp.getSession().disconnect();
} catch (JSchException e) {
log.error(e.getMessage());
}
sftp.quit();
sftp.disconnect();
}
public static void main(String[] args) throws IOException {
final String host = "127.0.0.0";
final int port = 2222;
final String username = "xxxx";
final String password = "123456";
String directory = "/app";
SftpUtils sf = SftpUtils.getInstance();
sf.connect(host,port,username,password);
File download = sf.download(directory,"20231226.txt", "D:\\tmp\\20231226.txt");
System.out.println(download.getName());
sf.disconnect();
}
}```