jsch 打开链接后下载多个文件
时间: 2023-10-04 14:11:24 浏览: 42
您可以使用 JSch 库来进行 SSH 连接和文件传输。下面是一个示例代码,它可以从远程服务器下载多个文件:
```java
import com.jcraft.jsch.*;
public class DownloadFiles {
public static void main(String[] args) {
String user = "username";
String password = "password";
String host = "remotehost";
int port = 22;
String remoteFolder = "/path/to/remote/folder/";
String[] filesToDownload = {"file1.txt", "file2.txt", "file3.txt"};
JSch jsch = new JSch();
Session session = null;
try {
// Create a new SSH session
session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
// Download each file in the list
for (String fileName : filesToDownload) {
String remoteFilePath = remoteFolder + fileName;
String localFilePath = "C:\\Users\\username\\Downloads\\" + fileName;
// Create a new channel for SFTP
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
// Download the file from the remote server
sftpChannel.get(remoteFilePath, localFilePath);
// Disconnect the SFTP channel
sftpChannel.disconnect();
}
// Disconnect the SSH session
session.disconnect();
System.out.println("Files downloaded successfully.");
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}
```
在这个示例代码中,我们连接到远程服务器,然后通过 SFTP 协议下载每个文件。您需要将 `user`、`password` 和 `host` 替换为您的实际值,并将 `remoteFolder` 替换为您要从中下载文件的远程文件夹的路径。您还需要将 `filesToDownload` 替换为要下载的实际文件名的数组。最后,您需要将 `localFilePath` 替换为您要将每个文件下载到的本地文件夹的路径。