# Sftp文件上传和下载工具类

news2024/9/17 8:22:31

## 依赖

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>





        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.21</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>

## 工具类SftpUtils

@Component
@Slf4j
public class SftpUtils {


public ChannelSftp sftp;
    public boolean isReady = false;
    public FtpConfig config;
    public Session sshSession;





    @Data
    private class FtpConfig {

        private String server;
        private String port;
        private String username;
        private String password;
        private String encoding;
    }







    /**
     * 连接sftp服务器
     */
    public SftpUtils(String server, String port, String username, String password, String encoding) {
        config = new FtpConfig();
        config.setServer(server);
        config.setPort(port);
        config.setUsername(username);
        config.setPassword(password);
        config.setEncoding(encoding);
        log.info("server = {}, port = {}, username = {}, password = {}", server, port, username, password);
    }





public void setReady() throws Exception {
        try {
            if (!isReady) {
                JSch jsch = new JSch();
                sshSession = jsch.getSession(config.getUsername(), config.getServer(), Integer.parseInt(config.getPort()));
                log.info("Session created.");
                sshSession.setPassword(config.getPassword());
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sshSession.setConfig(sshConfig);
                isReady = true;
                log.info("Session is ready.");
            }
            if (sshSession != null && !sshSession.isConnected()) {
                sshSession.connect();
                Channel channel = sshSession.openChannel("sftp");
                channel.connect();
                sftp = (ChannelSftp) channel;
                Class<ChannelSftp> c = ChannelSftp.class;
                Field f = c.getDeclaredField("server_version");
                f.setAccessible(true);
                f.set(sftp, 2);
                sftp.setFilenameEncoding(config.getEncoding());
                log.info("Session is connected.");
            }
        } catch (Exception e) {
            this.close();
            log.error("sftp连接服务器出错,host:" + config.getServer(), e);
            throw e;
        }
    }






    /**
     * 判断目录是否存在
     * @param directory
     * @return
     */
    public boolean isDirExist(String directory, ChannelSftp sftp)
    {
        boolean isDirExistFlag = false;
        try
        {
            sftp.cd(directory);
            isDirExistFlag = true;
        }
        catch (Exception e)
        {
            if (e.getMessage().equalsIgnoreCase("no such file"))
            {
                isDirExistFlag = false;
            }
        }finally {
            return isDirExistFlag;
        }
    }






    /**
     * 创建文件夹
     */
    public void createFolder(String sourceFolder){
        try {
            sftp.mkdir(sourceFolder);
        }catch (SftpException e){
            e.printStackTrace();
        }
    }






    /**
     * 设置编码格式
     */
    public void setEncoding(){
        try {
            Class cl = sftp.getClass();
            Field field = cl.getDeclaredField("server_version");
            field.setAccessible(true);
            field.set(sftp,2);
            sftp.setFilenameEncoding("GBK");
        }catch (Exception e){
            e.printStackTrace();
        }

    }





    /**
     * 上传文件
     * @param filePath
     * @param fileName
     * @param file
     * @return
     * @throws Exception
     */
    public boolean uploadFile(String filePath, String fileName, File file) throws Exception {
        log.info("directory:{},downloadFile:{},saveFile:{}", filePath, fileName, file);
        try {
            setReady();
            // sftp.cd(filePath);
            sftp.put(new FileInputStream(file), fileName);
            return true;
        } catch (Exception e) {
            log.error("sftp上传文件出错,fileName:" + fileName, e);
            throw e;
        }
    }







    /**
     * 列出目录下的文件
     *
     * @param directory 文件所在目录
     * @throws Exception
     */
    public List<String> listFiles(String directory) throws Exception {
        log.info("directory:{}", directory);
        setReady();
        Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory);
        if (vector.isEmpty()) {
            return Collections.emptyList();
        }
        return vector.stream().map(ChannelSftp.LsEntry::getFilename).collect(Collectors.toList()).stream().filter(file -> !".".equals(file) && !"..".equals(file)).collect(Collectors.toList());
    }





    /**
     * 删除文件
     *
     * @param directory
     *            要删除文件所在目录
     * @param deleteFile
     *            要删除的文件
     * @param sftp
     */
    public void delete(String directory, String deleteFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }










}

## 压缩工具类

public class ZipUtil {


    /**
     * 将文件压缩成zip
     *
     * @param sourceFile 源文件或目录,如:archive.tar
     * @param targetFile 目标文件,如:archive.tar.zip
     */
    public static void compress(String sourceFile, String targetFile) {
        long d1 = System.currentTimeMillis();
        try (OutputStream fos = new FileOutputStream(targetFile);
             OutputStream bos = new BufferedOutputStream(fos);
             ArchiveOutputStream aos = new ZipArchiveOutputStream(bos);){
            Path dirPath = Paths.get(sourceFile);
            Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    ArchiveEntry entry = new ZipArchiveEntry(dir.toFile(), dirPath.relativize(dir).toString());
                    aos.putArchiveEntry(entry);
                    aos.closeArchiveEntry();
                    return super.preVisitDirectory(dir, attrs);
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    ArchiveEntry entry = new ZipArchiveEntry(
                            file.toFile(), dirPath.relativize(file).toString());
                    aos.putArchiveEntry(entry);
                    IOUtils.copy(new FileInputStream(file.toFile()), aos);
                    aos.closeArchiveEntry();
                    return super.visitFile(file, attrs);
                }
            });
        } catch (IOException e) {
            System.out.println("压缩失败,原因:" + e.getMessage());
        }
        System.out.println("压缩完毕,耗时:" + (System.currentTimeMillis() - d1) + " ms");
    }




























}

## 测试类

@Slf4j
public class SftpTest {


@Test
    public void uploadTest() throws IOException {
        SftpUtils sftpUtils = new SftpUtils("IP", "port", "username", "password", "UTF-8");
        try {
            sftpUtils.setReady();

            // 本地目录
            String localPath = ("D:"+ File.separator + "game" + File.separator);
            // 文件名称
            String fileName = "植物大战僵尸";
            // 服务器目录
            // String sftpPath = ("File.separator" + "opt" + "File.separator" + "pvz" + "File.separator ");
            String sftpPath = ("/" + "opt" + "/" + "pvz" + "/");
            // 文件格式
            String suffix = ".zip";


            String localFilePath = localPath + fileName + suffix;

            String sftpFilePath = sftpPath + fileName + suffix;

            String localFolder = localPath + fileName;

            log.info("local:" + localFilePath);

            log.info("sftp:" + sftpFilePath);


            // 本地文件
            File file = new File(localFilePath);

            File fileFolder = new File(localFolder);


            // 文件不存在则压缩文件
            if (file.exists()){
                boolean deleteFlag = file.delete();
                if (deleteFlag){
                    log.info("删除成功!");
                }else {
                    throw new Exception("删除失败!");
                }
            }

            // 文件夹存在则压缩文件夹
            if (fileFolder.exists()){
                ZipUtil.compress(localFolder , localFilePath);
            }else {
                throw new Exception("文件夹不存在,请确认!");
            }


            // 设置编码格式
            sftpUtils.setEncoding();


            // 判断服务器是否需要创建文件夹
            if (sftpUtils.isDirExist(sftpPath,sftpUtils.sftp)){
                sftpUtils.sftp.cd(sftpPath);
            }else {
                sftpUtils.createFolder(sftpPath);
            }


            // 删除服务器上的旧文件
            sftpUtils.delete(sftpPath,fileName,sftpUtils.sftp);



            // 展示文件
            List<String> fileList1 = sftpUtils.listFiles(sftpPath);
            log.info("上传前目录列表:");
            fileList1.forEach(System.out::println);
            // System.out.println("上传前服务器文件:");
            // for (String f:fileList1){
            //     System.out.println(f);
            // }

            // 上传
            boolean result = sftpUtils.uploadFile(localFilePath,fileName + suffix,file);


            // 展示文件
            List<String> fileList2 = sftpUtils.listFiles(sftpPath);
            System.out.println("上传后目录列表:");
            fileList2.forEach(System.out::println);
            // for (String f:fileList2){
            //     System.out.println(f);
            // }


            if (result){
                log.info("上传成功!");
            }else {
                log.info("上传失败!");
            }



        }catch (Exception e){
            log.error(e.getMessage());
        }finally {
            sftpUtils.close();
        }
    }



























}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2040005.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Redmi 13C 5G 红米13R 5G 解锁BL 降级 MIUI 秒解锁BL 澎湃OS 降级

机型名称 &#xff1a;Redmi 13C 5G/ Redmi 13R 5G/ POCO M6 5G 机型代号 &#xff1a;air HyperOS 降级MIUI 14 澎湃OS 或者miui都可以秒解锁BL&#xff0c; Redmi 13C 5G 红米13R 5G 解锁BL 降级 MIUI 秒解锁BL 澎湃OS 降级,手机ROM - Powered by Discuz!点击上方 下载对…

大迈u盘文件不见了怎么办?全面解析与恢复策略

在数字化时代&#xff0c;U盘作为我们日常工作、学习和生活中不可或缺的存储设备&#xff0c;承载着大量的重要文件。然而&#xff0c;面对突如其来的U盘文件丢失问题&#xff0c;许多用户往往会感到手足无措&#xff0c;甚至因此遭受不可估量的损失。本文将围绕“大迈U盘文件丢…

算法与数据结构笔记

算法是什么 算法定义 算法&#xff08;algorithm&#xff09;是在有限时间内解决特定问题的一组指令或操作步骤&#xff0c;它具有以下特性。 ‧ 问题是明确的&#xff0c;包含清晰的输入和输出定义。 ‧ 具有可行性&#xff0c;能够在有限步骤、时间和内存空间下完成。 ‧…

多种方案解决IOS下uni.share分享分包页面报错Error: Framework inner error

项目场景&#xff1a; 有个需求是用uni.share从app分享微信小程序&#xff0c;发现在苹果手机真机调试的时候 跳转的目标页面会白屏、页面样式错乱、一些组件不出现等问题。并且报错 Error: Framework inner error 问题描述 uniapp开发在苹果手机下app分享微信小程序会出现白…

Golang | Leetcode Golang题解之第336题回文对

题目&#xff1a; 题解&#xff1a; // 哈希表实现 class Solution {public List<List<Integer>> palindromePairs(String[] words) {List<List<Integer>> res new ArrayList<>();int n words.length;Map<String, Integer> indices ne…

Nvidia显卡在深度学习应用中一些概念解释

之前一直在搞深度学习&#xff0c;最近又想着安装一下mamba试一下效果&#xff0c;可以配置环境就花了好长时间&#xff0c;主要还是一些概念没有弄明白&#xff0c;这里记录一下&#xff0c;方便以后查阅。 Nvidia显卡在深度学习应用中一些概念解释 显卡中一些名词的解释CUDA …

ZooKeeper集群环境部署

1. ZooKeeper安装部署 1.1 系统要求 1.1.1 支持的平台 ZooKeeper 由多个组件组成。一些组件得到广泛支持&#xff0c;而另一些组件仅在较小的一组平台上得到支持。 客户端是 Java 客户端库&#xff0c;由应用程序用于连接到 ZooKeeper 集群。 服务器是在 ZooKeeper 集群节点…

服务器主要有什么用途?什么情况下需要服务器?

服务器主要用于在网络中提供各种服务和资源。它们是现代信息技术基础设施的核心组成部分&#xff0c;用于存储、处理和管理数据&#xff0c;并为客户端设备&#xff08;如个人电脑、移动设备等&#xff09;提供所需的服务。以下是服务器的一些主要用途&#xff1a; 文件共享与存…

shell 三剑客-sed

sed 是Linux 系统一款非常强大的非交互式的文本编辑器&#xff0c;可以对文本进行增删改查操作&#xff0c;正则匹配文本内容。适合大文件编辑 sed 语法 sed 选项 ‘指令’ 文件 sed 选项 -f 包含sed指令的文件 文件 常用参数 -i&#xff1a;直接修改文件内容&#xff0c;而不…

用R语言运用 Shiny 包打造基于鸢尾花数据集的交互式数据可视化应用

下面内容摘录自《R 语言与数据科学的终极指南》专栏文章的部分内容&#xff0c;每篇文章都在 5000 字以上&#xff0c;质量平均分高达 94 分&#xff0c;看全文请点击下面链接&#xff1a; 1章4节&#xff1a;数据可视化&#xff0c; R 语言的静态绘图和 Shiny 的交互可视化演…

普通人看清房价走势的简单方法

研究了很多宏观方面的房价影响因素&#xff0c;还是很容易被看空和看多的房地产文章左右&#xff0c;也容易受到各种影响。 针对普通人而言&#xff0c;想要看清房价走势非常简单的一个方法&#xff0c; 你就看看你的工作状态【或者身边找工作的人多不多】 当你能挑工作的时…

老友记台词 第一季 第十三集 Friends 113(全英版)

文章目录 113 The One With the Boobies[Scene: Monica and Rachels, Chandler walks in and starts raiding the fridge. Then Rachel comes out of the shower with a towel wrapped round her waist, drying herself with another towel. Chandler and Rachel startle each …

CSC5613C 同步降压DC/DC

CSC5613C是一款同步降压型的DCDC变换器 IC&#xff0c;其输入电压为8~30V&#xff0c;具有良好的瞬态响应和环路稳定性。CSC5613C外围元器件极少&#xff0c;具有线补、过流保护和热保护功能。可通过调节FB电阻比例,来调整输出电压可用于快充。CSC5613C带载启动电流与其最大输出…

地下管线三维建模工具MagicPipe3D V3.5.2发布

经纬管网建模系统MagicPipe3D&#xff0c;本地离线参数化构建地下管网三维模型&#xff08;包括管道、接头、附属设施等&#xff09;&#xff0c;输出标准3DTiles、Obj模型等格式&#xff0c;支持Cesium、Unreal、Unity、Osg等引擎加载进行三维可视化、语义查询、专题分析&…

WPF窗体动态效果

在浏览网页的时候&#xff0c;发现现在很多网页都采用这种效果。看起来很炫。 效果如下&#xff1a; 已经实现很久了&#xff0c;一直没写出来。今天突然想到&#xff0c;写出来分享一下 原理比较简单&#xff0c;就是在Window里面放一个MediaElement控件&#xff0c;播放视频…

shell命令行解释器—既陌生有熟悉的东西

今天做一个感性的认识来&#xff0c;用一个生活的例子。 你生活在有一条村子里面&#xff0c;在村的东边就是王婆&#xff0c;王婆呢&#xff1f;她主要做什么呢啊&#xff1f;她在村儿里面呢&#xff0c;也不种地啊&#xff0c;那她干什么呢&#xff1f;他主要做帮别人进行婚嫁…

人工智能时代,网络安全公司F5如何提高防护效能?

随着AI推动的应用和API数量迅速增长&#xff0c;企业面临着日益严峻的安全挑战&#xff0c;亟需采取有效措施来应对。AI正将数字体验推向一个全新的高度&#xff0c;它通过分布式部署数据源、模型和服务在企业内部、云端和边缘计算环境中&#xff0c;并依靠不断扩展的API网络实…

旋转字符串 | LeetCode-796 | 模拟 | KMP | 字符串匹配

&#x1f64b;大家好&#xff01;我是毛毛张! &#x1f308;个人首页&#xff1a; 神马都会亿点点的毛毛张 &#x1f579;️KMP算法练习题 LeetCode链接&#xff1a;796. 旋转字符串 文章目录 1.题目描述&#x1f351;2.题解&#x1fad0;2.1 暴力解法&#x1fad2;2.2 模拟…

Go调度器

线程数过多,意味着操作系统会不断地切换线程,频繁的上下文切换就成了性能瓶颈.Go提供一种机制 可以在线程中自己实现调度,上下文切换更轻量,从而达到线程数少,而并发数并不少的效果,而线程中调度的就是Goroutine 调度器主要概念: 1.G:即Go协程,每个go关键字都会创建一个协程…

opencv基础的图像操作

1.读取图像&#xff0c;显示图像&#xff0c;保存图像 #图像读取、显示与保存 import numpy as np import cv2 imgcv2.imread(./src/1.jpg) #读取 cv2.imshow("img",img) #显示 cv2.imwrite("./src/2.jpg",img) #保存 cv2.waitKey(0) #让程序进入主循环(让…