依赖
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
代码
package com.cyz;
import com.jcraft.jsch.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
/**
* @author cyz
* @since 2024/6/6 下午3:50
*/
public class TestFtp {
static String server = "192.168.1.174";
static int port = 22;
static String user = "root";
static String pass = "2023#111";
private static ChannelSftp sftp = null;
static Channel channel = null;
static Session sshSession = null;
public static void main(String[] args) {
connect(server, user, pass, port);
put("/export/home/ftp/syncFile", new File("C:\\develop\\codes\\mycode\\callwebservicetest\\src\\main\\resources\\a.txt"));
logout();
}
public static void connect(String server, String username, String password, int port) {
System.out.println("FtpClient connect to server: ip[{" + server + "}], username:[{" + username + "}], password:[{" + password + "}], port:[{" + port + "}]");
try {
JSch jsch = new JSch();
jsch.getSession(username, server, port);
sshSession = jsch.getSession(username, server, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("connect success!");
} catch (JSchException e) {
e.printStackTrace();
throw new RuntimeException("FTP服务器连接失败", e);
}
}
public static void put(String remotePath, File file) {
System.out.println("FtpClient put [{" + file.getAbsolutePath() + "}] to [{" + remotePath + "}] ]");
FileInputStream inputStream = null;
try {
sftp.cd(remotePath);
inputStream = new FileInputStream(file);
sftp.put(inputStream, file.getName());
System.out.println("upload [" + file.getName() + "] success!");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException" + e.getMessage());
throw new RuntimeException("文件不存在", e);
} catch (SftpException e) {
System.out.println("SftpException" + e.getMessage());
throw new RuntimeException("上传失败", e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 关闭连接 server
*/
public static void logout() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
}
}
System.out.println("FtpClient logout success!");
}
}
测试