导入依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
或者jar包
import com.jcraft.jsch.*
上传文件
public static void upload(String username,String password,String host,int port,String filePath,String uploadFile) {
Session sshSession = null;
ChannelSftp sftp = null;
try {
//创建链接
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
//发送文件、
sftp.cd(filePath);
System.out.println("-------上传文件-------:"+uploadFile);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
System.out.println("-------上传完成-------:"+filePath);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sftp.isConnected()) {
sshSession.disconnect();
sftp.disconnect();
}
}
}
测试方法
public static void main(String[] args) {
String filePath="/test/zhanglm/";
String host="127.0.0.1";
int sftpPort=22;
String username="root";
String password="123456";
String localFilePath="D:\\test\\";
String fileName = "test.txt";
upload(username,password,host,sftpPort,filePath,localFilePath + fileName);
}