//引入依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version> <!-- 使用适合你项目的版本 -->
</dependency>
//以下为链接sftp和关闭操作
private static ChannelSftp sftp = null;
private static Session session = null;
/**
* 连接sftp服务器
*
* @param username
* @param password
* @param host
* @param port
* @param privateKey
* @return
*/
public static ChannelSftp sftpConnect(String username, String password, String host,
int port, String privateKey) throws Exception {
JSch jsch = new JSch();
if (privateKey != null && !"".equals(privateKey)) {
jsch.addIdentity(privateKey);// 设置私钥
}
//用户名,主机,端口号
session = jsch.getSession(username, host, port);
//密码
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
// 设置timeout时间
session.setTimeout(30000);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
return sftp;
}
/**
* 列出目录下的文件
*
* @param directory 要列出的目录
*/
public static Vector<?> listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
/**
* 关闭ftp连接
*/
public static void closeChannel() {
if (sftp != null) {
sftp.disconnect();
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
//以下为测试操作,可以创建main方法测试 *请注意上方代码块要和测试代码在一起,否则会报空 指针
String host = "*****";
int port = 22;
String username = "*****";
String password = "****";
String ftpPath = "/";
Map<String, Object> map = new HashMap<>();
try {
//创建连接
sftpConnect(username, password, host, port, null);
} catch (Exception e) {
e.printStackTrace();
}
try {
//获取文件列表
Vector vector = listFiles(ftpPath);
Iterator iterator = vector.iterator();
System.out.println("文件列表:");
int mix = 0;
String fileName = "";
for (int i = 0; i < vector.size(); i++) {
ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
// mTime 是更新时间,一下逻辑是获取最新上传的文件
int mTime = file.getAttrs().getMTime();
if (mTime >= mix) {
mix = mTime;
fileName = file.getFilename();
}
System.out.println(mTime);
}
// 以下是下载文件操作
sftp.cd(ftpPath);
FileOutputStream output = new FileOutputStream(new File(imgPath + "/" +
fileName));
sftp.get(fileName, output);
output.close();
} catch (SftpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeChannel();
}