Fork me on GitHub

Java上传本地文件到ftp服务器

1、引入maven依赖

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
</dependency>

2、相关工具类

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;

@Slf4j
public class Scpclient {

    private static Scpclient instance;

    public static synchronized Scpclient getInstance(String IP, int port, String username, String password) {
        if (instance == null) {
            instance = new Scpclient(IP, port, username, password);
        }
        return instance;
    }

    public Scpclient(String IP, int port, String username, String password) {
        this.ip = IP;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    /**
     * 远程上传文件
     * @param localFile 本地文件路径
     * @param remoteTargetDirectory  远程存放文件路径
     */
    public void putFile(String localFile, String remoteTargetDirectory) {
        Connection conn = new Connection(ip,port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (!isAuthenticated) {
                log.error("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            client.put(localFile, remoteTargetDirectory);
            conn.close();
        } catch (IOException e) {
            log.error("文件上传错误:{}", e);
        }
    }

    private String ip;
    private int port;
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }

}

3、上传文件代码

Scpclient scpclient = Scpclient.getInstance("176.16.18.123", 22,"user", "mypassword");
scpclient .putFile(localpath, "/home/myfile");;
posted @ 2021-05-18 15:08  ayueC  阅读(555)  评论(0)    收藏  举报