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 小时前
Jpa使用union all
java·spring boot·后端
用户3721574261351 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊2 小时前
Java学习第22天 - 云原生与容器化
java
渣哥4 小时前
原来 Java 里线程安全集合有这么多种
java
间彧4 小时前
Spring Boot集成Spring Security完整指南
java
间彧5 小时前
Spring Secutiy基本原理及工作流程
java
Java水解6 小时前
JAVA经典面试题附答案(持续更新版)
java·后端·面试
洛小豆8 小时前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试
前端小张同学8 小时前
服务器上如何搭建jenkins 服务CI/CD😎😎
java·后端
ytadpole8 小时前
Spring Cloud Gateway:一次不规范 URL 引发的路由转发404问题排查
java·后端