java实现上传文件到sftp
时间: 2023-09-03 16:07:13 浏览: 82
可以使用JSch库来实现Java上传文件到SFTP(SSH File Transfer Protocol)服务器。下面是一个简单的示例代码:
```java
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.Channel;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class SftpUploader {
public static void main(String[] args) {
String host = "sftp.example.com";
int port = 22;
String username = "your-username";
String password = "your-password";
String localFilePath = "/path/to/local/file.txt";
String remoteDir = "/path/to/remote/directory/";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
sftpChannel.put(inputStream, remoteDir + localFile.getName());
sftpChannel.disconnect();
session.disconnect();
System.out.println("File uploaded successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在代码中,你需要替换以下内容:
- `host`: SFTP服务器的主机名或IP地址
- `port`: SFTP服务器的端口号(默认为22)
- `username`: SFTP服务器的用户名
- `password`: SFTP服务器的密码
- `localFilePath`: 要上传的本地文件的路径
- `remoteDir`: 远程服务器上存储文件的目录路径
这段代码将建立与SFTP服务器的连接,然后使用`ChannelSftp`对象将本地文件上传到远程目录中。最后,它会输出"File uploaded successfully."来表示文件上传成功。
请确保在运行代码之前,你已经在项目的类路径中包含了JSch库的依赖。
相关推荐
![](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)
![](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)
![](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)
![](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)