java实现sftp下载文件
时间: 2023-12-27 21:04:30 浏览: 81
以下是使用JSch库进行SFTP下载的Java示例代码:
```java
import com.jcraft.jsch.*;
import java.io.*;
public class SFTPDownload {
public static void main(String[] args) {
String remoteFile = "/path/to/remote/file";
String localFile = "/path/to/local/file";
String username = "username";
String password = "password";
String host = "hostname";
int port = 22;
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.get(remoteFile, new FileOutputStream(localFile));
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (channelSftp != null) {
channelSftp.disconnect();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
}
```
该示例代码使用JSch库连接到远程服务器,下载指定路径的文件到本地。需要替换示例代码中的`remoteFile`、`localFile`、`username`、`password`、`host`和`port`变量为实际的值。
阅读全文