一、引入jar包
<dependency>
<groupId>com.github.mwiede</groupId>
<artifactId>jsch</artifactId>
<version>0.2.4</version>
</dependency>
二、工具类
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
* @Author yangxihui
* @Date 2022-10-25 15:09
* @Description
*/
public class SFtpUtil {
private Session sftp=null;
/**
* 链接远程sftp
* @param remote_Host
* @param user_name
* @param pass_word
* @param port
* @return
* @throws JSchException
*/
private ChannelSftp setupJsch(String remote_Host,String user_name,String pass_word, int port) throws JSchException {
JSch jsch = new JSch();
Session jschSession = jsch.getSession(user_name, remote_Host);
sftp=jschSession;
jschSession.setPassword(pass_word);
jschSession.setPort(port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
jschSession.setConfig(config);
jschSession.connect();
return (ChannelSftp) jschSession.openChannel("sftp");
}
/**
* 文件上传
* @param fileName
* @param localPath
* @param remotePath
* @return
*/
public boolean uploadFile(String fileName,String localPath,String remotePath,String remote_Host,String user_name,String pass_word, int port) {
try {
ChannelSftp channelSftp = setupJsch(remote_Host,user_name,pass_word,port);
channelSftp.connect();
channelSftp.put(localPath+ fileName, remotePath + fileName);
channelSftp.exit();
//关闭链接
logout();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 文件下载
* @param fileName
* @param localPath
* @param remotePath
* @return
*/
public boolean downdFile(String fileName,String localPath,String remotePath,String remote_Host,String user_name,String pass_word, int port) {
try {
ChannelSftp channelSftp = setupJsch(remote_Host,user_name,pass_word,port);
channelSftp.connect();
channelSftp.get(remotePath+ fileName, localPath + fileName);
channelSftp.exit();
//关闭链接
logout();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 关闭sftp连接
*/
public void logout(){
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
}
public static void main(String[] args) {
SFtpUtil sFtpUtil=new SFtpUtil();
String fileName="fileName.txt";
String localFile = "\data\test\";
String remoteDir = "\home\mytest\sk\";
String remote_Host = "222.11.22.111";
String user_name = "name";
String pass_word = "pwd";
int port =22;
boolean b = sFtpUtil.uploadFile(fileName, localFile, remoteDir,remote_Host,user_name,pass_word,port);
System.out.println("b = " + b);
}