jsch 下载sftp文件 代码
时间: 2024-05-13 20:15:54 浏览: 111
下面是使用 jsch 库下载 sftp 文件的代码示例:
```java
import com.jcraft.jsch.*;
import java.io.*;
public class SftpDownloader {
public static void main(String[] args) {
String host = "sftp.example.com";
int port = 22;
String username = "username";
String password = "password";
String remoteFilePath = "/path/to/remote/file.txt";
String localFilePath = "C:\\path\\to\\local\\file.txt";
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();
InputStream inputStream = channelSftp.get(remoteFilePath);
OutputStream outputStream = new FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
channelSftp.disconnect();
session.disconnect();
System.out.println("File downloaded successfully!");
} catch (JSchException | SftpException | IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们首先建立了一个与 SFTP 服务器的连接。然后我们打开了一个 SFTP 渠道,并使用 `get` 方法从服务器下载文件。最后,我们将从服务器下载的文件保存到本地磁盘。
请注意,这个示例假定你已经安装了 jsch 库并将其添加到类路径中。如果你使用 Maven 或 Gradle 等构建工具,请在构建文件中添加 jsch 依赖项。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)