java ftp文件上传sftp文件上传

复制代码
	<dependency>
		<groupId>commons-net</groupId>
		<artifactId>commons-net</artifactId>
		<version>3.6</version>
	</dependency>

	<!-- sftp -->
	<dependency>
		<groupId>com.jcraft</groupId>
		<artifactId>jsch</artifactId>
		<version>0.1.54</version>
	</dependency>

ftp:

java 复制代码
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FtpTest {

    public static void main(String[] args) {
        ftpUploadFile("192.168.1.129", 21, "root", "123456",
                "D:\\test-ftp.txt",
                "/usr/soft");
    }
    /**
     * ftp上传单个文件
     *
     * @param hostname       服务器地址
     * @param port           端口号
     * @param username       用户名
     * @param password       密码
     * @param uploadFilePath 上传文件路径(包括文件名)
     * @param destPath       ftp上传目录
     */
    public static void ftpUploadFile(String hostname, int port, String username, String password, String uploadFilePath, String destPath) {

        System.out.println("准备连接到ftp");
        try {
            FTPClient ftp = new FTPClient();
            //连接
            ftp.connect(hostname, port);
            //登录
            boolean loginS = ftp.login(username, password);
            if (!loginS) {
                System.out.println("ftp登录失败,用户名或密码错误");
                return;
            } else {
                System.out.println("ftp登录成功");
            }
            // 获取本地文件并上传
            String file = uploadFilePath;
            FileInputStream input = new FileInputStream(file);
            ftp.changeWorkingDirectory(destPath);//跳转目录
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//必须要设置以二进制的方式传输文件
            ftp.enterLocalPassiveMode();//被动模式
            file = new String(file.getBytes("GBK"), "iso-8859-1");

            if (!ftp.storeFile(new File(file).getName(), input)) {
                System.out.println("失败,服务器返回:" + ftp.getReplyString());//获取上传失败的原因
            } else {
                System.out.println("文件:" + new File(file).getName() + " 上传成功");
            }
            input.close();
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("ftp连接失败");
        }
    }
    
}

sftp:

java 复制代码
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

public class SfptTest {
    public static void main(String[] args) {

        uploadFile("D:\\test-ftp.txt",
                "/usr/soft/",
                "root", "123456",
                "192.168.1.130", 22);
    }
    
    /**
     * @param filePath 文件全路径
     * @param ftpPath  上传到目的端目录
     * @param username
     * @param password
     * @param host
     * @param port
     */
    public static void uploadFile(String filePath, String ftpPath, String username, String password, String host, Integer port) {
        FileInputStream input = null;
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            //获取session  账号-ip-端口
            com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
            //添加密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            //严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            //开启session连接
            sshSession.connect();
            //获取sftp通道
            sftp = (ChannelSftp) sshSession.openChannel("sftp");
            //开启
            sftp.connect();
            //文件乱码处理
            /*Class<ChannelSftp> c = ChannelSftp.class;
            Field f = c.getDeclaredField("server_version");
            f.setAccessible(true);
            f.set(sftp, 2);
            sftp.setFilenameEncoding("GBK");*/
            //判断目录是否存在
            try {
                Vector ls = sftp.ls(ftpPath); //ls()得到指定目录下的文件列表
                /*if (ls == null) {   //ls不会为null,哪怕它是一个空目录
                    sftp.mkdir(ftpPath);
                }*/
            } catch (SftpException e) {
                sftp.mkdir(ftpPath);
            }
            sftp.cd(ftpPath);
            String filename = filePath.substring(filePath.lastIndexOf(File.separator) + 1); //附件名字
            //filename = new String(filename.getBytes("GBK"), StandardCharsets.ISO_8859_1);
            input = new FileInputStream(new File(filePath));
            sftp.put(input, filename);
            //设定777权限,转为8进制放入chmod中
            //sftp.chmod(Integer.parseInt("777", 8), ftpPath + filename);
            input.close();
            sftp.disconnect();
            sshSession.disconnect();
            System.out.println("================上传成功!==================");
        } catch (Exception e) {
            System.out.println("================上传失败!==================");
            e.printStackTrace();
        }
    }

    /**
     * @param directory    SFTP服务器的文件路径
     * @param downloadFile SFTP服务器上的文件名
     * @param saveFile     保存到本地路径
     * @param username
     * @param password
     * @param host
     * @param port
     */
    public static void downloadFile(String directory, String downloadFile, String saveFile, String username, String password, String host, Integer port) throws JSchException, IOException {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            //获取session  账号-ip-端口
            com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
            //添加密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            //严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            //开启session连接
            sshSession.connect();
            //获取sftp通道
            sftp = (ChannelSftp) sshSession.openChannel("sftp");
            //开启
            sftp.connect();
            if (directory != null && !"".equals(directory)) {
                sftp.cd(directory);
            }
            FileOutputStream output = new FileOutputStream(new File(saveFile));
            sftp.get(downloadFile, output);
            output.close();
            sftp.disconnect();
            sshSession.disconnect();
            System.out.println("================下载成功!==================");
        } catch (SftpException | FileNotFoundException | JSchException e) {
            System.out.println("文件下载异常!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
相关推荐
微石科技1 分钟前
医疗设备维保如何从被动维修转向预防管理?宁波微石科技让运行数据提前发信号
java·后端·struts
SomeB1oody6 分钟前
【RustyML入门】5.1. 回归指标
开发语言·后端·机器学习·rust·教程
学计算机的计算基7 分钟前
TCP 传输层硬核整理:三次握手、四次挥手、拥塞控制一次讲透
java·网络·笔记·网络协议·算法
龙虾PRO17 分钟前
2026 DeepSeek Harness 部署完整教程:npx 一键启动至 Python SDK 全流程接入
开发语言·python
都叫我大帅哥24 分钟前
@EnableTransactionManagement 详解:Spring 声明式事务的基石
java·spring
2602_959960921 小时前
大厂Java面试:Spring Boot、JVM、Redis、Kafka与Elasticsearch在内容社区UGC场景下的实战拷问
java·jvm·spring boot·redis·面试题
小新讲网安2 小时前
WiFi安全攻防实战:WPA3新协议与传统破解技术全解析
开发语言·网络·安全·php·漏洞·nmap·漏洞检测
必须会一定会8 小时前
Agent Plugins 1.0实战:plugin.json、skills、mcp.json目录结构与迁移
开发语言·人工智能·ai编程
St_rive9 小时前
Page Object设计模式
java·开发语言·设计模式
wp123_19 小时前
硬件元器件笔记|IPX8 防水 Type‑C 母座安费诺 124018802112A 与 TONEVEE TY48086‑24A 分析
c语言·开发语言·笔记