封装成一个jar包,引入依赖的方式
pom依赖
测试时候本地起一个虚拟机
<dependency>
<groupId>itcast</groupId>
<artifactId>sftp-spring-boot-starter</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/sftp-spring-boot-starter-1.0.0.jar</systemPath>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
示例代码
@Component
public class SftpServiceImpl implements SftpService {
@Autowired
private final SftpTemplate sftpTemplate;
public SftpServiceImpl(SftpTemplate sftpTemplate) {
this.sftpTemplate = sftpTemplate;
}
@Override
public void upload() throws FileNotFoundException {
String localDir="D:\\1.txt";
//传到服务器后的名称
String name="sftp.txt";
File file=new File(localDir);
InputStream is=new FileInputStream(file);
String dir="/root/";
sftpTemplate.upload(dir,name,is);
System.out.println("文件上传成功");
}
}
配置(sftp连接信息)
sftp:
pool:
min-idle: 1
max-idle: 8
max-active: 8
max-wait: -1
test-on-borrow: true
test-on-return: false
test-while-idle: true
time-between-eviction-runs: 600000
min-evictable-idle-time-millis: 1800000
enabled-log: false
hosts:
# 地址的名字,你可以通过它来切换连接,默认名字是default
default:
# 密码登录
host: ip
port: 22
username: root
word: root