java使用sftp
时间: 2023-11-03 08:06:59 浏览: 50
要使用SFTP,需要使用JSch这个Java库。以下是一个简单的示例代码,可以连接到SFTP服务器并上传文件:
```java
import com.jcraft.jsch.*;
public class SftpExample {
public static void main(String[] args) {
String host = "sftp.example.com";
String username = "username";
String password = "password";
int port = 22;
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
String localFilePath = "/path/to/local/file.txt";
String remoteFilePath = "/path/to/remote/file.txt";
channelSftp.put(localFilePath, remoteFilePath);
channelSftp.disconnect();
session.disconnect();
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}
```