java连接sftp服务器
时间: 2023-08-30 22:09:03 浏览: 41
Java 可以使用 JSch 库连接 SFTP 服务器。以下是一个简单的示例:
```java
import com.jcraft.jsch.*;
public class SftpExample {
public static void main(String[] args) {
String username = "username";
String password = "password";
String hostname = "hostname";
int port = 22;
JSch jSch = new JSch();
try {
Session session = jSch.getSession(username, hostname, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
// 下载文件
channelSftp.get("/remote/path/to/file", "/local/path/to/file");
// 上传文件
channelSftp.put("/local/path/to/file", "/remote/path/to/file");
channelSftp.disconnect();
session.disconnect();
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们首先使用 JSch 创建一个会话,并设置用户名、密码、主机名和端口号。然后,我们连接到会话,并打开一个 SFTP 通道。通过通道,我们可以上传和下载文件。最后,我们断开连接。