springboot如何读取sftp的⽂件⽬录
springboot读取sftp的⽂件
1.添加pom依赖(基于springboot项⽬)
2.application.yaml配置⽂件
3.⼯具类
4.实际调⽤
springboot使⽤SFTP⽂件上传
springboot读取sftp的⽂件
1.添加pom依赖(基于springboot项⽬)
session如何设置和读取<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
2.application.yaml配置⽂件
sftp:
ip: 192.168.1.102
port: 22
username: admin
password: admin
root: /img #⽂件根⽬录
3.⼯具类
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.SftpException;
slf4j.Slf4j;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import urrent.TimeUnit;
/**
*
*/
@Slf4j
public class SFTPUtil {
/**
* 下载重试次数
*/
private static final int DOWNLOAD_RETRY = 3;
/
**
* 下载重试间隔时间单位毫秒
*/
private static final long DOWNLOAD_SLEEP = 3 * 1000;
private static final SFTPUtil SFTP = new SFTPUtil();
private static ChannelSftp client;
private static Session session;
/**
* @return
*/
public static SFTPUtil getInstance() {
return SFTP;
}
/**
* 获取SFTP连接
*
* @param username
* @param password
* @param ip
* @param port
* @return
*/
synchronized public ChannelSftp makeConnection(String username, String password, String ip, int port) {
if (client == null || session == null || !client.isConnected() || !session.isConnected()) {
try {
JSch jsch = new JSch();
session = Session(username, ip, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
// 设置第⼀次登陆的时候主机公钥确认提⽰,可选值:(ask | yes | no)
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
//sftp协议
Channel channel = session.openChannel("sftp");
client = (ChannelSftp) channel;
log.info("sftp connected success,connect to [{}:{}], username [{}]", ip, port, username);
} catch (JSchException e) {
<("sftp connected fail,connect to [{}:{}], username [{}], password [{}], error message : [{}]", ip, port, username, password, e.getMessage());            }
}
return client;
}
/**
*
* 关闭连接 server
*/
public static void close() {
if (client != null && client.isConnected()) {
client.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
/**
* 单次下载⽂件
*
* @param downloadFile 下载⽂件地址
* @param saveFile    保存⽂件地址
* @param ip          主机地址
* @param port        主机端⼝
* @param username    ⽤户名
* @param password    密码
* @param rootPath    根⽬录
* @return
*/
public synchronized static File download(String downloadFile, String saveFile, String ip, Integer port, String username, String password, String rootPath) {        boolean result = false;
File file = null;
Integer i = 0;
while (!result) {
//获取连接
ChannelSftp sftp = getInstance().makeConnection(username, password, ip, port);
FileOutputStream fileOutputStream = null;
log.info("sftp file download start, target filepath is {}, save filepath is {}", downloadFile, saveFile);
try {
sftp.cd(rootPath);
file = new File(saveFile);
if (ists()) {
file.delete();
} else {
}
fileOutputStream = new FileOutputStream(file);
<(downloadFile, fileOutputStream);
result = true;
} catch (FileNotFoundException e) {
<("sftp file download fail, FileNotFound: [{}]", e.getMessage());
} catch (IOException e) {
<("sftp file download fail, IOException: [{}]", e.getMessage());
} catch (SftpException e) {
i++;
<("sftp file download fail, sftpException: [{}]", e.getMessage());
if (i > DOWNLOAD_RETRY) {
<("sftp file download fail, retry three times, SftpException: [{}]", e.getMessage());                    return file;
}
try {
TimeUnit.MILLISECONDS.sleep(DOWNLOAD_SLEEP);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
SFTPUtil.close();
}
return file;
}
/**
* 下载⽂件
*
* @param downloadFile 下载⽂件的路径
* @param saveFile    保存的路径
* @param rootPath    根⽬录
* @return
*/
public synchronized static File download(String downloadFile, String saveFile, String rootPath) {
boolean result = false;
File file = null;
Integer i = 0;
while (!result) {
FileOutputStream fileOutputStream = null;
log.info("sftp file download start, target filepath is {}, save filepath is {}", downloadFile, saveFile);            try {
//获取连接、读取⽂件(ChannelSftp) session.openChannel("sftp")
client.cd(rootPath);
file = new File(saveFile);
if (ists()) {
file.delete();
} else {
}
fileOutputStream = new FileOutputStream(file);
<(downloadFile, fileOutputStream);
result = true;
} catch (FileNotFoundException e) {
<("sftp file download fail, FileNotFound: [{}]", e.getMessage());
} catch (IOException e) {
<("sftp file download fail, IOException: [{}]", e.getMessage());
} catch (SftpException e) {
i++;
<("sftp file download fail, sftpException: [{}]", e.getMessage());
if (i > DOWNLOAD_RETRY) {
<("sftp file download fail, retry three times, SftpException: [{}]", e.getMessage());                    return file;
}
try {
TimeUnit.MILLISECONDS.sleep(DOWNLOAD_SLEEP);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
}
4.实际调⽤
public class SFTP {
@Value("${sftp.ip}")
String ip;
@Value("${sftp.port}")
Integer port;
@Value("${sftp.username}")
String username;
@Value("${sftp.password}")
String password;
@Value("${}")
String rootPath;
@GetMapping("/test")
public void test() throws IOException {
File file= SFTPUtil.download(downloadFilePath, "1.txt", rootPath);
SFTPUtil.close();
InputStreamReader read = null;
BufferedReader bufferedReader = null;
String encoding = "utf-8";
try {
read = new InputStreamReader(new FileInputStream(file), encoding);
bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = adLine()) != null) {
log.info("[{}] downfile is [{}] ", username, lineTxt);
}
read.close();
bufferedReader.close();
file.delete();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (read != null) {
read.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (file != null && ists()) {
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
springboot使⽤SFTP⽂件上传
最近在⼯作功能使⽤了sftp做⽂件上传下载的功能,在这⾥简单的记录⼀下pom⽂件中引⼊相关的jar包
<!-- mvnrepository/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
建⽴springboot项⽬,在application.properties添加如下配置
sftp.ip=127.0.0.1
sftp.port=22
sftp.username=xuyy
sftp.password=paswpord
#ftp根⽬录
上⾯⼀sftp开头的都是⾃定义配置,需要写个配置类读取⼀下,⾃动注⼊到springboot中package com.fig;
import lombok.Data;
import org.t.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 特点:读取配置⽂件。可以对静态变量直接赋值
*
* @author xuyangyang
*/
@Component
@ConfigurationProperties(prefix = "sftp")
@Data
public class SftpConfig {
public static String ip;
public static Integer port;
public static String username;
public static String password;
public static String rootpath;
//注意这⾥是 static 修饰,便于sftputil直接取值
public static String getIp() {
return ip;
}
public void setIp(String ip) {
SftpConfig.ip = ip;
}
public static Integer getPort() {
return port;
}
public void setPort(Integer port) {
SftpConfig.port = port;
}
public static String getUsername() {
return username;
}
public void setUsername(String username) {
SftpConfig.username = username;
}
public static String getPassword() {
return password;
}
public void setPassword(String password) {
SftpConfig.password = password;
}
public static String getRootpath() {
return rootpath;
}
public void setRootpath(String rootpath) {
}
}
下⾯是具体的⼯具类,代码写的⽐较简单,可以⾃⼰下载优化⼀下,等我有时间在优化package com.uinnova.ftpsynweb.util;
import com.jcraft.jsch.*;
import com.fig.SftpConfig;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;
ansaction.SystemException;
import java.io.*;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。