import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.File;
import java.io.FileInputStream;
public class SFTPUploadExample {
public static void main(String[] args) {
String host = "your.sftp.server.com";
int port = 22;
String user = "username";
String password = "password";
String localFilePath = "/path/to/local/file.txt";
String remoteFilePath = "/path/to/remote/file.txt";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
// 禁用主机密钥检查
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
File file = new File(localFilePath);
FileInputStream fis = new FileInputStream(file);
sftpChannel.put(fis, remoteFilePath);
fis.close();
sftpChannel.exit();
session.disconnect();
System.out.println("File uploaded successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
com.jcraft.jsch
包,这是一个常用的 Java SFTP 库。你需要在项目中添加这个依赖。JSch
创建一个会话(Session
),并设置服务器的主机名、端口、用户名和密码。StrictHostKeyChecking
为 no
,这会在实际生产环境中带来安全风险,建议在生产环境中启用主机密钥检查。ChannelSftp.put()
方法将本地文件上传到远程服务器。请根据实际情况修改 host
、port
、user
、password
、localFilePath
和 remoteFilePath
的值。
上一篇:java抽象类有构造方法吗
下一篇:java继承父类
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站