ftp参数实体

public class FTPParameter {
private String host;private int port;private String user;private String pass;private String dir;  //下载路径private int mode;private int frequency;private int waitTime;private String localSavePath;private String upDir;//上传路径private String localSaveUpPath;//本地反馈文件路径public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public String getUpDir() {
return upDir;
}
public void setUpDir(String upDir) {
this.upDir = upDir;
}
public String getLocalSaveUpPath() {
return localSaveUpPath;
}
public void setLocalSaveUpPath(String localSaveUpPath) {
this.localSaveUpPath = localSaveUpPath;
}
public void setPort(int port) {
this.port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public int getMode() {
return mode;
}
public void setMode(int mode) {
this.mode = mode;
}
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
public int getWaitTime() {
return waitTime;
}
public void setWaitTime(int waitTime) {
this.waitTime = waitTime;
}
public String getLocalSavePath() {
return localSavePath;
}
public void setLocalSavePath(String localSavePath) {
this.localSavePath = localSavePath;
}  }//ftp处理类
public class FTPManager {
private static final Log logger = LogFactory.getLog(FTPManager.class);private static boolean initailized = false;
private static boolean ht_initailized = false;public static long FTP_ALERT = System.currentTimeMillis();public static boolean init(FTPParameter parameter, FTPClient ftp) {
initailized = false;
if (parameter != null) {
boolean connected = connect(parameter, ftp);
if (connected) {
logger.info("FTP Client连接成功,登录......");
} else {
return false;
}boolean logined = login(parameter, ftp);if (logined) {
logger.info("FTP Client登录成功,可以传输文件");
initailized = true;
} else {
logger.info("FTP Client登录失败。");
}return logined;
}return initailized;
}// 建立FTP连接
public static boolean connect(FTPParameter parameter, FTPClient ftp) {
try {
ftp.connect(parameter.getHost());
switch (parameter.getMode()) {
case 1:
ftp.enterLocalPassiveMode();
logger.info("FTP为本地被动模式");
break;
case 2:
ftp.enterRemotePassiveMode();
logger.info("FTP为远程被动模式");
break;
case 3:
ftp.enterRemoteActiveMode(InetAddress.getByAddress(parameter
.getHost().getBytes()), parameter.getPort());
logger.info("FTP为远程主动模式");
break;
case 0:
default:
ftp.enterLocalActiveMode();
logger.info("FTP为本地主动模式");
break;
}
return true;
} catch (SocketException e) {
logger.error("FTP Client连接主机失败:", e);
} catch (IOException e) {
logger.error("FTP Client连接主机失败:", e);
}
return false;
}// 登录FTP服务器
public static boolean login(FTPParameter parameter, FTPClient ftp) {
try {
return ftp.login(parameter.getUser(), parameter.getPass());
} catch (IOException e) {
logger.error("FTP Client登录主机失败:", e);
return false;
}
}public static boolean initailized() {
return initailized;
}// FTP上传文件
public static boolean sendFile(File file, FTPParameter parameter,
FTPClient ftp) {
try {
int reply;disconnect(ftp);
if (!init(parameter, ftp)) {
throw new RuntimeException("FTP Client未成功连接");
}logger.debug("FTP Client上传文件......");
// After connection attempt, you should check the reply code to
// verify
// success.
reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
logger.error("FTP server refused connection.");
return false;
}// FTPListParseEngine engine = ftp.initiateListParsing("JTbilling");
// 上传内容
FileInputStream fis = new FileInputStream(file);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
String filename = parameter.getDir() + "/" + file.getName()
+ ".TMP";
// 上传时先将文件命名为.TMP
boolean transComplated = ftp.storeFile(filename, fis);
fis.close();
logger.info(parameter.getDir() + "/" + file.getName() + ".TMP");
if (transComplated) {
// 上传结束后将文件名修改回来
transComplated = ftp.rename(parameter.getDir() + "/"
+ file.getName() + ".TMP", parameter.getDir() + "/"
+ file.getName());
if (transComplated)
logger.info("FTP上传文件" + file.getName() + "成功");
else
logger.info("FTP上传文件" + file.getName() + "失败");
} else
logger.info("FTP上传文件" + file.getName() + "失败1");return transComplated;
} catch (IOException e) {
logger.error("FTP Client 上传发生异常:", e);
return false;
} finally {
disconnect(ftp);
}
}// FTP下载文件
public static File getFile(String filename, File file,
FTPParameter parameter, FTPClient ftp) {
try {
int reply;disconnect(ftp);
if (!init(parameter, ftp)) {
throw new RuntimeException("FTP Client未成功连接");
}logger.debug("FTP Client下载文件......");
// After connection attempt, you should check the reply code to
// verify
// success.
reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
logger.error("FTP server refused connection.");
return null;
}// FTPListParseEngine engine = ftp.initiateListParsing("JTbilling");
// 下载内容
FileOutputStream fos = new FileOutputStream(file);
boolean transComplated = ftp.retrieveFile(parameter.getDir() + "/"
+ filename, fos);try {
fos.flush();
fos.close();
} catch (Exception e) {
}if (transComplated) {
logger.info("FTP下载文件成功");
return file;
} else {
logger.info("FTP下载文件失败");
return null;
}
} catch (IOException e) {
logger.error("FTP Client 下载发生异常:", e);
return null;
} finally {
disconnect(ftp);
}
}// 移动文件
public static boolean moveFile(String fileName, String dir,
FTPParameter parameter, FTPClient ftp) {
try {
int reply;disconnect(ftp);
if (!init(parameter, ftp)) {
throw new RuntimeException("FTP Client未成功连接");
}logger.debug("FTP Client移动文件......");
// After connection attempt, you should check the reply code to
// verify
// success.
reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
logger.error("FTP server refused connection.");
return false;
}// 移动文件
boolean transComplated = ftp.rename(parameter.getDir() + "/"
+ fileName, dir + "/" + fileName);
if (transComplated) {
logger.info("FTP移动文件" + fileName + "成功");
} else {
logger.info("FTP移动文件" + fileName + "失败");
}
return transComplated;
} catch (IOException e) {
logger.error("FTP Client 移动发生异常:", e);
return false;
} finally {
disconnect(ftp);
}
}// 下载所有文件到指定的地址
public static void getAllFile(String path, FTPParameter parameter,
FTPClient ftp) {
try {
int reply;disconnect(ftp);
if (!init(parameter, ftp)) {
throw new RuntimeException("FTP Client未成功连接");
}logger.debug("FTP Client下载所有文件......");
// After connection attempt, you should check the reply code to
// verify
// success.
reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
logger.error("FTP server refused connection.");
}// 获取所有的文件
FileOutputStream fos = null;
FTPFile[] fileList = ftp.listFiles(parameter.getDir());
for (int i = 0; i < fileList.length; i++) {
boolean transComplated = false;FTPFile ftpFile = fileList[i];
/*if (ftpFile.getName().equals("."))
continue;
if (ftpFile.getName().equals(".."))
continue;*/File file = new File(path + "/" + ftpFile.getName());
fos = new FileOutputStream(file);
transComplated = ftp.retrieveFile(parameter.getDir() + "/"
+ ftpFile.getName(), fos);
try {
Thread.sleep(parameter.getWaitTime() * 1000);
} catch (Exception e1) {
logger.info("下载文件" + ftpFile.getName()
+ "失败,等待下次下载时发生异常!", e1);
}if(transComplated)
ftp.deleteFile(parameter.getDir() + "/" + ftpFile.getName());try {
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
logger.error("FTP Client 下载所有文件发生异常:", e);
} finally {
disconnect(ftp);
}
}// 删除ftp过期文件
public static void delFtpFile(FTPParameter parameter, FTPClient ftp,
String realdir) {
try {
int reply;
disconnect(ftp);
if (!init(parameter, ftp)) {
throw new RuntimeException("FTP Client未成功连接");
}logger.debug("FTP Client删除过期文件......");
// After connection attempt, you should check the reply code to
// verify
// success.
reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
logger.error("FTP server refused connection.");
}// 获取所有的文件
FileOutputStream fos = null;
FTPFile[] fileList = ftp.listFiles(realdir);
long sysnow = System.currentTimeMillis();
Date systime = new Date(sysnow);
for (int i = 0; i < fileList.length; i++) {FTPFile ftpFile = fileList[i];
// 文件过期 就从FTP上删除
if ((ftpFile.getName().equals("."))
|| (ftpFile.getName().equals("..")))// 过滤文件名不正确的文件
continue;Date lastModifiedDate = fileList[i].getTimestamp().getTime();int times;// 文件最后修改时间与系统时间相差ms数
times = (int) ((systime.getTime()) - lastModifiedDate.getTime());
if (times >= (7 * (24 * 60 * 60 * 1000)))// 判断是否7天
{
ftp.deleteFile(realdir + "/" + ftpFile.getName());}try {
fos.flush();
fos.close();
} catch (Exception e) {
}
}
} catch (IOException e) {
logger.error("FTP Client 删除文件发生异常:", e);
} finally {
disconnect(ftp);
}
}// 删除本地过期文件/**
* 删除过期文件 注意:指定删除的文件为最后一次修改的文件日期,不是按照文件名也不是
* 文件所创建的日期。指定的path必须是目录名,否则函数不会执行并且没有返回值。
*
* @param day
*            天数
* @param path
*            路径目录名
*/
public static void delFile(String path) {
int day = 7;
// long dateNum;
Date date;
Date dateNow;
Calendar cal = Calendar.getInstance();
Calendar calNow = Calendar.getInstance();
File filepath = filePathPreProc(path);
File[] files;
try {
if (filepath.exists()) {
if (filepath.isDirectory()) {
files = filepath.listFiles();
for (int i = 0; i < files.length; i++) {
date = new Date(files[i].lastModified());
dateNow = new Date();
cal.setTime(date);
calNow.setTime(dateNow);
int dec = calNow.get(Calendar.DAY_OF_YEAR)
- cal.get(Calendar.DAY_OF_YEAR);
// 删除指定日期的文件
if (dec >= day) {
if (files[i].isFile()) {
files[i].delete();
}
}
}
}
}
} catch (Exception e) {
logger.error("本地删除文件发生异常:", e);
}}/**
* 文件路径预处理,将Windows或Unix like 路径转化为统一的Unix like路径,如果用户输入有误则返回null
*
* @param pathstr
* @return
*/
public static File filePathPreProc(String pathstr) {
pathstr = pathstr.replaceAll("\\\\", "/").trim();
Pattern p = Pattern.compile("(^\\.|^/|^[a-zA-Z])?:?/.+(/$)?");
Matcher m = p.matcher(pathstr);
// 不符合要求直接返回
if (!m.matches()) {
return null;
}
// 这里开始文件名已经符合要求
File path = new File(pathstr);
return path;
}// 关闭FTP连接
public static void disconnect(FTPClient ftp) {
if (ftp == null)
return;
if (ftp.isConnected()) {
try {
ftp.logout();
ftp.disconnect();
logger.info("FTP Client断开连接...");
} catch (IOException ioe) {
// do nothing
}
}
}}

ftp文件上传和下载相关推荐

  1. java 中 FtpClient 实现 FTP 文件上传、下载

    前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家.点击跳转到教程. 源代码大部分是网上找的,查来查去,找到几个可以用的例子,改来改去,揉合成现在这个样子. 一. jar ...

  2. 【SpringBoot】:springboot整合FTP文件上传与下载功能

    导入依赖包 <dependency><groupId>commons-net</groupId><artifactId>commons-net</ ...

  3. 使用API进行FTP文件上传和下载

    又有几天没发新贴了,刚才有点闲瑕,便随手写了一个使用FTP上传和下载文件的类. 类代码如下: Option Explicit'* *********************************** ...

  4. java中ftp删除文件,Java 实现ftp 文件上传、下载和删除

    实现FTP相关功能 1.下载相应的jar包 commons-net-3.6.jar 2.代码实现 import java.io.File; import java.io.FileInputStream ...

  5. C#编程, FTP文件上传、下载、重命名公共类

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net ...

  6. php从ftp下载文件到本地,php使用ftp实现文件上传与下载功能

    本文实例为大家分享了php ftp文件上传与下载的具体代码,供大家参考,具体内容如下 ftp文件上传 php自带有ftp操作的函数包,一个比较简单实现的ftp文件上传操作可以通过以下几个步骤来完成: ...

  7. python连接ftp并上传、下载文件

    # -*- coding:utf-8 -*- """ Created on 2019年12月11日 :封装FTP文件上传与下载函数 @author: dch " ...

  8. php vsftpd文件上传类,php ftp文件上传函数(基础版)

    php ftp文件上传函数(基础版) 复制代码 代码如下: // 定义变量 $local_file = 'local.zip'; $server_file = 'server.zip'; // 连接F ...

  9. java ftp 下载慢_Java实现ftp文件上传下载解决慢中文乱码多个文件下载等问题

    废话不多说了,直接给大家贴代码了,具体代码如下所示: //文件上传 public static boolean uploadToFTP(String url,int port,String usern ...

最新文章

  1. DOS命令输出的重定向
  2. TensorFlow、Numpy中的axis的理解
  3. php上传文件 不移动,move_uploaded_file()为什么无法移动上传的文件?
  4. Go 指针 unsafe.Pointer
  5. zbb20170606 oracle 查看空表
  6. 2015. A New Year Gift
  7. Android:一个线程玩转商品列表所有item的倒计时器,并对Adapter进行单控件刷新优化...
  8. 链表常见面试题二:约瑟夫环
  9. Redis配置文件配置
  10. 抽象类可以用new创建对象吗_宠物可以用人类的湿巾吗?猫咪有泪痕可以用纸巾擦掉吗?...
  11. tlc5620输出三角波流程图_TLC5620(电压输出型)_pdf
  12. pythonide的作用_你知道Python神器IDE是什么吗?
  13. Android自动播放下一曲,环信Android自动播放下一条语音
  14. WIFI智能音箱技术方案开发
  15. MSOCache文件夹能否删除?
  16. PHP毕业设计项目作品源码选题(9)学校校园教师排课系统毕业设计毕设作品开题报告
  17. 快解析内网穿透,速度快 不限速 不限流
  18. 小额信贷管理系统解决方案
  19. (2017中国数字化贡献人物专访)线上蓝光、数字蓝光:助力蓝光弯道超车
  20. PyGame每日一练——五子棋小游戏

热门文章

  1. 【机器学习】逻辑斯蒂回归原理推导与求解
  2. [86题更新完毕] 牛客Python专项题
  3. js 模拟浏览器的并行请求限制
  4. 【app测试】adb常用指令及华为卸载预置软件
  5. 【仓库物资识别】二、将三维点云转换成二维图像
  6. 【大学生活】优秀的有趣的博客
  7. C# 微信支付之JSAPI支付
  8. 快速实现免费的个人免签收款功能(不写一行代码)
  9. 解决办法:git错误 error: failed to push some refs to 'https://github.com/...
  10. Python 机器学习/深度学习/算法专栏 - 导读目录