java sftp 工具类
时间: 2023-09-23 19:02:52 浏览: 190
java实现sftp操作工具类
5星 · 资源好评率100%
您好!如果您想要使用Java进行SFTP操作,可以使用JSch库来实现。下面是一个示例的SFTP工具类,帮助您进行SFTP文件传输:
```java
import com.jcraft.jsch.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class SftpUtils {
private String host;
private int port;
private String username;
private String password;
public SftpUtils(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
}
public void uploadFile(String localFilePath, String remoteFilePath) throws JSchException, SftpException {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
File localFile = new File(localFilePath);
FileInputStream fis = new FileInputStream(localFile);
channel.put(fis, remoteFilePath);
fis.close();
channel.disconnect();
session.disconnect();
}
public void downloadFile(String remoteFilePath, String localFilePath) throws JSchException, SftpException {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
File localFile = new File(localFilePath);
FileOutputStream fos = new FileOutputStream(localFile);
channel.get(remoteFilePath, fos);
fos.close();
channel.disconnect();
session.disconnect();
}
public static void main(String[] args) {
String host = "your_sftp_host";
int port = 22;
String username = "your_username";
String password = "your_password";
String localFilePath = "local_file_path";
String remoteFilePath = "remote_file_path";
SftpUtils sftpUtils = new SftpUtils(host, port, username, password);
try {
// 上传文件
sftpUtils.uploadFile(localFilePath, remoteFilePath);
// 下载文件
// sftpUtils.downloadFile(remoteFilePath, localFilePath);
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}
```
您可以根据实际情况修改主机地址、端口、用户名、密码,以及本地文件路径和远程文件路径,然后在`main`方法中调用相关方法进行SFTP文件上传或下载。
请确保将JSch库添加到您的项目依赖中。希望对您有所帮助!如果有任何问题,请随时提问。
阅读全文