java中sftp下载文件
时间: 2023-11-20 20:55:33 浏览: 37
在Java中使用SFTP(Secure File Transfer Protocol)下载文件,你可以使用JSch库来实现。面是一个简单的示例代码:
```java
import com.jcraft.jsch.*;
public class SFTPDownloader {
public static void main(String[] args) {
String hostname = "sftp.example.com";
int port = 22;
String username = "your_username";
String password = "your_password";
String remoteFilePath = "/path/to/remote/file.txt";
String localFilePath = "/path/to/local/file.txt";
JSch jsch = new JSch();
Session session = null;
ChannelSftp channelSftp = null;
try {
session = jsch.getSession(username, hostname, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.get(remoteFilePath, localFilePath);
System.out.println("File downloaded successfully.");
} catch (JSchException | SftpException e) {
e.printStackTrace();
} finally {
if (channelSftp != null) {
channelSftp.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
}
```
在上述代码中,你需要将`hostname`、`port`、`username`和`password`替换为实际的SFTP服务器信息。同时,将`remoteFilePath`设置为要下载的远程文件路径,`localFilePath`设置为要保存到本地的文件路径。运行代码后,远程文件将被下载到指定的本地路径。
请确保在使用JSch之前,将其添加到你的项目中。你可以在这里下载JSch库:http://www.jcraft.com/jsch/