FTP实现文件夹上传

2023-11-05

···
package com.supcon.orchid.ChuanHuaCostom.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import org.apache.log4j.Logger;

public class FTPTest {
private FTPClient ftpClient;
private String strIp;
private int intPort;
private String user;
private String password;

private static Logger logger = Logger.getLogger(FTPTest.class.getName());

/* *
 * Ftp构造函数
 */
public FTPTest(String strIp, int intPort, String user, String Password) {
    this.strIp = strIp;
    this.intPort = intPort;
    this.user = user;
    this.password = Password;
    this.ftpClient = new FTPClient();
}
/**
 * @return 判断是否登入成功
 * */
public boolean ftpLogin() {
    boolean isLogin = false;
    FTPClientConfig ftpClientConfig = new FTPClientConfig();
    ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
    this.ftpClient.setControlEncoding("GBK");
    this.ftpClient.configure(ftpClientConfig);
    try {
        if (this.intPort > 0) {
            this.ftpClient.connect(this.strIp, this.intPort);
        }else {
            this.ftpClient.connect(this.strIp);
        }
        // FTP服务器连接回答
        int reply = this.ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            this.ftpClient.disconnect();
            logger.error("登录FTP服务失败!");
            return isLogin;
        }
        this.ftpClient.login(this.user, this.password);
        // 设置传输协议
        this.ftpClient.enterLocalPassiveMode();
        this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        logger.info("恭喜" + this.user + "成功登陆FTP服务器");
        isLogin = true;
    }catch (Exception e) {
        e.printStackTrace();
        logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
    }
    this.ftpClient.setBufferSize(1024 * 2);
    this.ftpClient.setDataTimeout(30 * 1000);
    return isLogin;
}

/**
 * @退出关闭服务器链接
 * */
public void ftpLogOut() {
    if (null != this.ftpClient && this.ftpClient.isConnected()) {
        try {
            boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
            if (reuslt) {
                logger.info("成功退出服务器");
            }
        }catch (IOException e) {
            e.printStackTrace();
            logger.warn("退出FTP服务器异常!" + e.getMessage());
        }finally {
            try {
                this.ftpClient.disconnect();// 关闭FTP服务器的连接
            }catch (IOException e) {
                e.printStackTrace();
                logger.warn("关闭FTP服务器的连接异常!");
            }
        }
    }
}

/***
 * 上传Ftp文件
 * @param localFile 当地文件
 * @param romotUpLoadePath上传服务器路径 - 应该以/结束
 * */
public boolean uploadFile(File localFile, String romotUpLoadePath) {
    BufferedInputStream inStream = null;
    boolean success = false;
    try {
        this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
        inStream = new BufferedInputStream(new FileInputStream(localFile));
        logger.info(localFile.getName() + "开始上传.....");
        success = this.ftpClient.storeFile(localFile.getName(), inStream);
        if (success == true) {
            logger.info(localFile.getName() + "上传成功");
            return success;
        }
    }catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error(localFile + "未找到");
    }catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (inStream != null) {
            try {
                inStream.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return success;
}

/***
 * 下载文件
 * @param remoteFileName   待下载文件名称
 * @param localDires 下载到当地那个路径下
 * @param remoteDownLoadPath remoteFileName所在的路径
 * */

public boolean downloadFile(String remoteFileName, String localDires,
                            String remoteDownLoadPath) {
    String strFilePath = localDires + remoteFileName;
    BufferedOutputStream outStream = null;
    boolean success = false;
    try {
        this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
        outStream = new BufferedOutputStream(new FileOutputStream(
                strFilePath));
        logger.info(remoteFileName + "开始下载....");
        success = this.ftpClient.retrieveFile(remoteFileName, outStream);
        if (success == true) {
            logger.info(remoteFileName + "成功下载到" + strFilePath);
            return success;
        }
    }catch (Exception e) {
        e.printStackTrace();
        logger.error(remoteFileName + "下载失败");
    }finally {
        if (null != outStream) {
            try {
                outStream.flush();
                outStream.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    if (success == false) {
        logger.error(remoteFileName + "下载失败!!!");
    }
    return success;
}

/***
 * @上传文件夹
 * @param localDirectory
 *            当地文件夹
 * @param remoteDirectoryPath
 *            Ftp 服务器路径 以目录"/"结束
 * */
public boolean uploadDirectory(String localDirectory,
                               String remoteDirectoryPath) {
    File src = new File(localDirectory);
    try {
        remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
        boolean makeDirFlag = this.ftpClient.makeDirectory(remoteDirectoryPath);
        System.out.println("localDirectory : " + localDirectory);
        System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
        System.out.println("src.getName() : " + src.getName());
        System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
        System.out.println("makeDirFlag : " + makeDirFlag);
        // ftpClient.listDirectories();
    }catch (IOException e) {
        e.printStackTrace();
        logger.info(remoteDirectoryPath + "目录创建失败");
    }
    File[] allFile = src.listFiles();
    for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
        if (!allFile[currentFile].isDirectory()) {
            String srcName = allFile[currentFile].getPath().toString();
            uploadFile(new File(srcName), remoteDirectoryPath);
        }
    }
    for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
        if (allFile[currentFile].isDirectory()) {
            // 递归
            uploadDirectory(allFile[currentFile].getPath().toString(),
                    remoteDirectoryPath);
        }
    }
    return true;
}

/***
 * @下载文件夹
 * @param localDirectoryPath本地地址
 * @param remoteDirectory 远程文件夹
 * */
public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
    try {
        String fileName = new File(remoteDirectory).getName();
        localDirectoryPath = localDirectoryPath + fileName + "//";
        new File(localDirectoryPath).mkdirs();
        FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
        for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
            if (!allFile[currentFile].isDirectory()) {
                downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
            }
        }
        for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
            if (allFile[currentFile].isDirectory()) {
                String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
                downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
            }
        }
    }catch (IOException e) {
        e.printStackTrace();
        logger.info("下载文件夹失败");
        return false;
    }
    return true;
}
// FtpClient的Set 和 Get 函数
public FTPClient getFtpClient() {
    return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
    this.ftpClient = ftpClient;
}

public static void sentFile(){
    FTPTest ftp=new FTPTest("10.100.0.207",2123,"FTP_SRP","1QA2ws3ed");
    ftp.ftpLogin();
    System.out.println("1");
    //上传文件夹
    boolean uploadFlag = ftp.uploadDirectory("D:\\supPlant\\bap-server\\bap-workspace\\uploads\\2020", "\\"); //如果是admin/那么传的就是所有文件,如果只是/那么就是传文件夹
    System.out.println("uploadFlag : " + uploadFlag);
    //下载文件夹
    ftp.downLoadDirectory("d:\\tm", "/");
    ftp.ftpLogOut();

    }

}
···

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

FTP实现文件夹上传 的相关文章

  • warning: #223-D: function “strlen“ declared implicitly

    问题描述 在使用Keil5编译C文件时报错 warning 223 D function strlen declared implicitly 问题解决 在主函数中加入 extern size t strlen const char
  • continue与break --- 循环控制的两大巨头

    目录 前言 break continue 总结 前言 continue与break都是用于循环语句的 帮助我们更好的控制循环流程 我们以while循环为例 来深度解析continue与break语句 这是while语句的基本结构 结合con
  • FastDFS安全注意事项

    FastDFS安全注意事项 本篇文章转载于 FastDFS 作者 余庆 大佬的 FastDFS分享与交流 公众号 对于互联网应用 FastDFS 的标准使用姿势 通过 FastDFS API 进行文件上传等更新操作 storage serv
  • Jmeter(二十八) - 从入门到精通 - Jmeter Http协议录制脚本工具-Badboy1(详解教程)

    1 简介 在使用jmeter自动录制脚本时会产生很多无用的请求 所以推荐使用badboy录制脚本之后保存为jmx文件 在jmeter中打开使用 因此宏哥在这里介绍一下Badboy这款工具 本来打算不做介绍了 原因是因为这款工具已经不在维护和
  • python-selenium-弹窗的处理

    切换到弹窗视角 alert driver switch to alert 点击弹窗中的确认 alert accept 点击弹窗中的取消 alert dismiss 获取弹出框的信息内容 alert text 当遇到弹窗时 1 切换到弹窗视角
  • Android Socket详细使用攻略

    前言 Socket的使用在 Android网络编程中非常重要 今天我将带大家全面了解 Socket 及 其使用方法 目录 1 网络基础 1 1 计算机网络分层 计算机网络分为五层 物理层 数据链路层 网络层 运输层 应用层 其中 网络层 负
  • C语言第一次作业练习

    以下程序教材基于 谭浩强C程序设计 第四版 第1题 参照例1 3 在Visual C 6 0环境中继续完成教材P 15 习题6 此程序于2017年3月1日12 48编写 目的 当用户在命令窗口输入a b c三个值 输出 其中最大者 incl
  • windows10下配置android-studio-ide

    前言 android studio ide配置对于新手来说可能有一点点麻烦 这里详细记录一下 希望对新手有所帮助 大佬请忽略哈 下载 android studio ide官网下载地址 谷歌官网的这个地址目前对天朝开放 android stu
  • C#判断字符串中有没有字母,正则表达式、IsLetter

    要判断字符串中是否包含字母 可以使用正则表达式或者循环遍历字符串的方式 方法一 使用正则表达式 using System Text RegularExpressions string input Hello123 bool contains
  • 单例模式、工厂模式,观察者模式

    单例模式 Singleton 限制了类的实例化次数只能一次 从经典意义来将 单例模式 在实例不存在的时候 可以通过一个方法创建一个类来实现创建类的新实例 如果实例已经存在 他会简单返回该对象的引用 单例模式不同于静态类 可以推迟它们的初始化
  • csharp:Dapper Sample

    You can find Dapper on Google Code here http code google com p dapper dot net and the GitHub distro here https github co
  • Redis集群的那些谜

    下列问题是我在搭建Redis集群之前与实验过程发出的疑问 随着我Redis集群的成功搭建 疑问也一个一个解开 Redis集群搭建参考资料 Redis Cluster参考资料 Redis集群的数据互通吗 先说结论 互通的 往Redis集群里存
  • hualinux dj3 2.6:drf ViewSets使用@action添加路由及传参

    目录 一 viewSets active修饰器介绍 1 1 介绍 1 2 用法 二 例子 2 1 需求 2 2 分析 2 2 1 action自定义路由 2 2 2 action url path不支持尖括号传参问题 2 3 实现代码 2
  • 杂项记录

    2019 07 14 查看一些基础的信息 比如CPU 逻辑核等系你 查看某个网卡在哪个numa节点上https blog csdn net jpmsdn article details 84561294 DPDK最大支持核数 128 在rt
  • cmake安装更新(解决cmake报错:CMake 3.8 or higher is required. You are running version 3.5.1)

    ubuntu16 04在安装libfreenect过程中 出现cmake报错 CMake 3 8 or higher is required You are running version 3 5 1 cmake3 5 1是在安装ubunt
  • Linux查看用户UID和所属组

    使用以下命令查看 id 用户名 如省略用户名代表查看当前用户的
  • SQL注入1——显注(重学)

    SQL注入 学习自 文章 201 A3 SQL注入 上 视频 农夫安全201 A3 sql注入技巧上2 SQL注入 SQL注入 前言 一 显注 1 判断 2 判断字段数量 3 获取数据库信息 4 获取表信息 5 获取列信息 6 获取表信息
  • 配置虚拟机,查看主机cpu个数

    打开 任务管理器 性能 资源监视器 CPU 即可查看 根据自身cpu个数不同分配虚拟机处理器个数 我这里是有8个cpu
  • LeetCode 高级 - 矩阵中的最长递增路径

    矩阵中的最长递增路径 给定一个整数矩阵 找出最长递增路径的长度 对于每个单元格 你可以往上 下 左 右四个方向移动 你不能在对角线方向上移动或移动到边界外 即不允许环绕 示例 1 输入 nums 9 9 4 6 6 8 2 1 1 输出 4
  • Idea+git push时候出现HTTP 413 错误

    Delta compression using up to 4 threads Compressing objects 100 2364 2364 done Writing objects 100 4329 4329 1 15 MiB 11

随机推荐

  • 【java】计算员工工资

    案例介绍 任务描述 某公司有多个部门 员工信息包含姓名 name 类型 type 部门 department 和底薪 basicSalary 其中员工的类型有三种 管理员 销售员和工人 公司财务部门工作人员每月要计算员工的实发工资 实发工资
  • Windows端高仿超级逼真Mac系统方法

    简介 MyDock是一款完全免费的高仿Mac桌面的主题软件 软件仿造Mac系统桌面高达95 以上的相似度 不管是主题样式 界面 功能 操作方式 都达到了仿造Mac系统的效果 Mac系统有的功能 这里基本上都有 如Dock图标的鱼眼放大效果
  • idea显示连接https://start.spring.io连接问题

    表示尴尬 jar包没有打出来 还给我弄了个错误 用spring initializr方式创建一个spring boot项目给我来个 当时就懵逼了 在网上看到说吧https改成http 看了好几种方式 但对我有用的是在idea里的settin
  • flex写Java词法分析_如何用flex+bison写语法分析器

    背景 这个星期 项目中要使用C 或C语言解析JSON格式的数据 把解析的结果放到一个通用的数据结构 这个通用的数据结构 实际上是作为web服务层 这一层大家可以认为是类似于PHP服务器或webpy的服务器容器 到web页面层 这一层是语法类
  • Java使用list集合remove需要注意的事项

    在实际开发中有时候会碰到这样的场景 需要将一个list集合中的某些特定的元素给删除掉 这个时候用可以用List提供的remove方法来实现需求 List中的remove方法传入的参数可以是集合的下标 也可以是集合中一个元素 也可以是一个集合
  • 我的专业我做主ppt计算机,我的专业我做主(会计专业入门知识).ppt

    我的专业我做主 会计专业入门知识 ppt 由会员分享 可在线阅读 更多相关 我的专业我做主 会计专业入门知识 ppt 13页珍藏版 请在装配图网上搜索 1 会计学原理 姓名 池泽周 学院 经济管理学院 班级 会计092班 会计学原理是会计学
  • 对于制造业来说,MES上线前后有哪些变化?

    对于制造业来说 MES软件系统未上线前的现状 具体如下 1 目前 制造业产品的批次记录仍然是手工录入 并且每批都需要去打印 除此之外 生产过程中的投料量计算结果 产品测试的申请单 月生产计划表 产品所需浓度的计算都需要人工填写 不仅需要耗费
  • python包管理-pip

    镜像列表 官方 已默认添加 豆瓣 清华大学 中国科技大学 阿里 网易镜像 腾讯镜像 华为镜像 北京外国语大学 哈尔滨工业大学 百度 https pypi python org simple http pypi doubanio com si
  • 基于爱奇艺HCDN视频分发网络的开放缓存

    为通过Internet向海量用户传输高清晰度 高码率的视频节目 爱奇艺融合CDN和P2P技术 开发出一套适合多终端的混合分发传输网络 HCDN 本文来自爱奇艺高级技术总监庹虎在LiveVideoStackCon 2018大会中的演讲 由Li
  • CTF-8 靶场夺旗

    兵无常势 水无常形 能因敌而致胜者 谓之神 环境准备 VMware Workstation Pro12 Kali Linux IP 10 10 16 128 CTF 8 虚拟机 NAT 网络连接 1 主机发现 fping asg 10 10
  • ubuntu10上安装万能五笔

    我听同事说ubuntu上运行eclipse会比window上快 我抱着好奇就安装了ubuntu来试玩玩 安装完毕 上网找资料的时候 发现我需要中文输入 尤其是五笔 后来返回到window上上网搜索 找到了些资料 知道如何通过ibus来使用拼
  • java泛型里能放多个类吗,具有多个类的Java泛型通配符

    小编典典 实际上 你可以做你想做的事 如果要提供多个接口或一个类加接口 则必须使通配符看起来像这样 请参见sun com上的泛型教程 特别是页面底部的 绑定类型参数 部分 实际上 如果需要 你可以列出多个接口 并 InterfaceName
  • Spring Boot 3.0学习笔记

    什么是Spring Boot Spring Boot是一个基于Spring Framework的快速开发Web应用的工具 它使用了约定优于配置的方式来快速构建应用 使得开发人员能够专注于业务逻辑的实现 而不用过多关注配置和框架集成问题 Sp
  • iostat 工具分析I/O性能

    iostat命令用途 主要用于监控系统设备的IO负载情况 iostat首次运行时显示自系统启动开始的各项统计信息 之后运行iostat将显示自上次运行该命令以后的统计信息 用户可以通过指定统计的次数和时间来获得所需的统计信息 iostat有
  • 若依框架密码验证环节修改(三方登录时改为跳过密码验证,但正常登录保留密码验证)

    当用到三方登录时 例如微信登录等 没法验证密码 又找不到若依密码的解密方式 套用此方法 跳过密码验证 并且为可选的 想让哪个方法登录时要密码或者不要 写上即可 我使用的是若依不分离版 但参考自官方文档 大差不差 具体见个人情况 参考地址 若
  • 【学习笔记】数据获取之爬虫笔记

    概述 疫情期间在风变编程 https www pypypy cn 上学习了爬虫的相关知识 风变编程是一个交互式学习网站 目前开的模块还不是很多但是交互式在线教学实验的形式还是十分有趣 交互式的形式教一个读书顺序 督催一行一行读书 告诉什么时
  • 网页唤起QQ在线聊天

    免费版 详见 https shang qq com v3 widget html 示例 a href http wpa qq com msgrd v 3 uin 1078363295 site qq menu yes 在线客服 a 目前还能
  • 【华师】C++简答题汇总

    简答题 斜体和代码块都是了解即可 面向对象四大特征 封装 抽象 继承 多态 对象 客观世界中的任何一个事物都可以视作一个对象 任何一个对象都己有两个要素 属性和行为 属性是对象本身的性质 而行为是对象的功能 C 中每个对象都是由数据和函数组
  • unity 项目强制退出通知服务器,MonoBehaviour.OnApplicationQuit() 当应用程序退出 - Unity5 中文 API 手册...

    Description 描述 Sent to all game objects before the application is quit 在应用退出之前发送给所有的游戏物体 In the editor this is called wh
  • FTP实现文件夹上传

    package com supcon orchid ChuanHuaCostom util import java io BufferedInputStream import java io BufferedOutputStream imp