java中编写代码:如何以sftp的形式把文件上传到服务器?

在Java中,你可以使用JSch库来实现通过SFTP(SSH File Transfer Protocol)将文件上传到服务器。以下是一个示例代码,展示了如何使用JSch库进行SFTP文件上传:

import com.jcraft.jsch.*;

public class SftpUploader {
    public static void main(String[] args) {
        String host = "服务器主机名";
        int port = 22;
        String username = "用户名";
        String password = "密码";
        String localFilePath = "本地文件路径";
        String remoteFilePath = "远程服务器文件路径";

        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); // 上传文件
            System.out.println("文件上传成功");
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null && channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}

请确保将代码中的服务器主机名用户名密码本地文件路径远程服务器文件路径替换为实际的值。此示例假设你已经添加了JSch库到项目的类路径中。

猜你喜欢

转载自blog.csdn.net/gb4215287/article/details/132265659