多线程 上传一个文件到sftp Java实现
时间: 2023-09-20 14:11:41 浏览: 187
可以使用JSch库来实现在Java中上传文件到SFTP服务器的功能,以下是一个简单的示例代码:
```java
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class SftpUploader {
private String host;
private int port;
private String username;
private String password;
private String remoteDirectory;
public SftpUploader(String host, int port, String username, String password, String remoteDirectory) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.remoteDirectory = remoteDirectory;
}
public void uploadFile(String localFilePath, String remoteFilename) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.cd(remoteDirectory);
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
sftpChannel.put(inputStream, remoteFilename);
inputStream.close();
sftpChannel.exit();
session.disconnect();
}
}
```
在上面的代码中,`SftpUploader`类的构造函数接收SFTP服务器的主机名、端口号、用户名、密码和远程目录路径。`uploadFile`方法接收本地文件路径和远程文件名,然后将文件上传到远程SFTP服务器。可以在多个线程中创建`SftpUploader`实例并调用`uploadFile`方法来同时上传多个文件。
阅读全文