一.导入JSch依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
二.用SFTP将文件(txt等)上传到远程服务器
public class SFTPUploader {
public static void main(String[] args) {
String host = "sftp.example.com"; //远程服务器地址
String username = "username"; //服务器账号
String password = "password"; //服务器密码
int port = 22;
String localFilePath = "localfile.txt"; //需要上传的文件
String remoteDirectoryPath = "/path/to/remote/directory/";//上传到服务器的路径
JSch jsch = new JSch();
Session session = null;
ChannelSftp channelSftp = null;
try {
session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
channelSftp.cd(remoteDirectoryPath);
channelSftp.put(inputStream, localFile.getName());
System.out.println("File uploaded successfully");
} catch (JSchException | SftpException | java.io.IOException e) {
e.printStackTrace();
} finally {
if (channelSftp != null) {
channelSftp.exit();
}
if (session != null) {
session.disconnect();
}
}
}
}