sftp上传下载文件 java
时间: 2023-07-05 10:37:03 浏览: 117
您可以使用JSch库来实现在Java中使用SFTP上传和下载文件。以下是一个示例代码片段:
```java
import com.jcraft.jsch.*;
public class SftpExample {
public static void main(String[] args) {
String user = "sftp_username";
String password = "sftp_password";
String host = "sftp_hostname";
int port = 22;
try{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
// Download file from SFTP server
String remoteFile = "/path/to/remote/file.txt";
String localFile = "/path/to/local/file.txt";
channelSftp.get(remoteFile, localFile);
// Upload file to SFTP server
String remoteDir = "/path/to/remote/directory/";
String localFile2 = "/path/to/local/file2.txt";
channelSftp.put(localFile2, remoteDir);
channelSftp.exit();
session.disconnect();
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}
```
请记得替换示例代码中的用户名、密码、主机名、端口、远程和本地文件路径,以适应您的情况。
阅读全文