In Java, you can use the JSch library to upload files to the server via SFTP (SSH File Transfer Protocol). Here is a sample code showing how to use the JSch library for SFTP file upload:
import com.jcraft.jsch.*;
public class SftpUploader { public static void main(String[] args) { String host = "server hostname"; int port = 22; String username = "username"; String password = "password"; String localFilePath = "local file Path"; String remoteFilePath = "Remote server file path";
JSch jSch = new JSch();
Session session = null;
ChannelSftp channelSftp = null;
try {
session = jSch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.put(localFilePath, remoteFilePath); // Upload file
System.out.println("File uploaded successfully");
} catch (JSchException | SftpException e) { e.printStackTrace(); } finally { if (channelSftp != null && channelSftp.isConnected()) { channelSftp.disconnect(); } if (session != null && session.isConnected()) { session.disconnect(); } } } }
服务器主机名
Make sure to replace , 用户名
, 密码
, 本地文件路径
and in the code 远程服务器文件路径
with actual values. This example assumes you have added the JSch library to your project's classpath.