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 小时前
医院陪诊管理系统怎么选择?——2026 年选型避坑与架构参考
java·开发语言·陪诊系统·陪诊app·医院陪诊陪护
CodeStats1 小时前
【Spring事务】Spring事务注解 @Transactional 完整体系:从 MySQL 隔离级别到 MyBatis 原理详解
java·spring·mybatis·事务·transactional
我命由我123452 小时前
Android 开发问题:为 PDFView 设置一个带有黑色边框的背景 drawable,但边框没有生效
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
爱写代码的小朋友3 小时前
从零开始学 Win32 API:C++ 窗口编程实战(VS Code + MinGW-w64 命令行详解)
开发语言·c++
果汁华3 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
小小晓.4 小时前
C++:语句和作用域
开发语言·c++
都叫我大帅哥4 小时前
从Python到Java:为什么企业级Agent最终会选择Java?
java·ai编程
wanderist.4 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
海天鹰5 小时前
PHP上传文件
android·开发语言·php
腻害兔6 小时前
【若依项目-产品经理视角】RuoYi-Vue-Pro 源码拆解:IM 即时通讯模块,一个被低估的「全功能聊天系统」
java·前端·vue.js·产品经理·ai编程