SFTP文件上传-下载

发布时间 2023-05-22 17:16:13作者: 黄河大道东
import cn.hutool.extra.ssh.Sftp;
import cn.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * @author JHL
 * @version 1.0
 * @date 2023/5/19 10:24
 * @since : JDK 11
 */
public class SftpUtil {

    private static final Logger logger = LoggerFactory.getLogger(SftpUtil.class);

    private static final String TMP_DIR = System.getenv("TMP");

    // private static final ApplicationTemp APPLICATION_TEMP = new ApplicationTemp();

    private static final String HOST = "47.xxx.xxx.101";

    private static final Integer PORT = 22;

    private static final String ACCOUNT = "root";

    private static final String PASSWORD = "xxxx";

    /**
     * 获取客户端
     */
    public static Sftp sftpClient() {
        return new Sftp(HOST, PORT, ACCOUNT, PASSWORD);
    }

    /**
     * 上传文件到指定路径下
     */
    public static Boolean uploadFile(String destPath, String absoluteFilePath) {
        Sftp client = sftpClient();
        boolean result = client.upload(destPath, new File(absoluteFilePath));
        logger.info("######################### \t[ 上传本地文件[ {} ],至远程服务器路径[ {} ],上传结果[ {} ]]\t #########################", absoluteFilePath, destPath, result);
        client.close();
        return result;
    }

    /**
     * 下载远程文件到本地
     * 例如下载:https://www.xxx.cn/6666.jpg
     */
    public static String downloadRemoteFile(String url) {
        String[] split = url.split("/");
        String fileName = "";
        for (int i = 0; i < split.length; i++) {
            if (i == split.length - 1) {
                fileName = split[i];
            }
        }
        // String absoluteFilePath = APPLICATION_TEMP.getDir().getPath() + File.separator + fileName;
        String absoluteFilePath = TMP_DIR + File.separator + fileName;
        long size = HttpUtil.downloadFile(url, new File(absoluteFilePath));
        logger.info("######################### \t[ 下载远程:{} 资源,大小:{},到本地路径: {} ]\t #########################", url, size, absoluteFilePath);
        return absoluteFilePath;
    }
}