JSch Maven地址
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
java代码实现
import com.jcraft.jsch.*; public class SFTPUploader { public static void main(String[] args) { String host = "服务器地址"; String username = "用户名"; String password = "密码"; int port = 22; String localFilePath = "本地文件路径"; String remoteDirectoryPath = "服务器目录路径"; Session session = null; ChannelSftp channelSftp = null; try { JSch jsch = new JSch(); session = jsch.getSession(username, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); // 获取本地文件名和路径 String localFileName = localFilePath.substring(localFilePath.lastIndexOf("/") + 1); String localFilePathWithoutName = localFilePath.substring(0, localFilePath.lastIndexOf("/")); // 将本地文件上传到服务器并重命名为.tmp channelSftp.put(localFilePath, remoteDirectoryPath + "/" + localFileName + ".tmp"); // 修改文件名为原名 channelSftp.rename(remoteDirectoryPath + "/" + localFileName + ".tmp", remoteDirectoryPath + "/" + localFileName); System.out.println("文件上传成功!"); } catch (JSchException | SftpException e) { e.printStackTrace(); System.out.println("文件上传失败!"); } finally { if (channelSftp != null) { channelSftp.disconnect(); } if (session != null) { session.disconnect(); } } } }