1、需求:某公司ftp服务器中一个文件夹中有30个文件(文件名字是不同的),每五分钟产生一个新的文件,同时删除这三十个文件中最早产生的文件,该文件夹中始终保持30个文件。

  现在需要采集一周的数据做研究。

  解决思路,用java扫描该文件夹,把所有产生的新文件保存到本地一个目录下,文件名持久化一个文本中,防止FTP出问题。一周后可以得到这一周的数据。

下面是代码:

  1. package cim;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.OutputStream;
  8. import java.net.SocketException;
  9. import java.util.List;
  10.  
  11. import org.apache.commons.net.ftp.FTPClient;
  12. import org.apache.commons.net.ftp.FTPFile;
  13. import org.apache.commons.net.ftp.FTPReply;
  14. import org.apache.log4j.Logger;
  15.  
  16. public class FtpUtil {
  17. static Logger logger = Logger.getLogger(FtpUtil.class);
  18. /**
  19. * 获取FTPClient对象
  20. *
  21. * @param ftpHost
  22. * FTP主机服务器
  23. * @param ftpPassword
  24. * FTP 登录密码
  25. * @param ftpUserName
  26. * FTP登录用户名
  27. * @param ftpPort
  28. * FTP端口 默认为21
  29. * @return
  30. */
  31. static FTPClient ftpClient = null;
  32.  
  33. public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
  34. String ftpPassword, int ftpPort) {
  35. try {
  36. ftpClient = new FTPClient();
  37. ftpClient.setControlEncoding("GBK");
  38. ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
  39. ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
  40. if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
  41. logger.info("未连接到FTP,用户名或密码错误。");
  42. close();
  43. } else {
  44. // logger.info("FTP连接成功。");
  45. }
  46. } catch (SocketException e) {
  47. e.printStackTrace();
  48. logger.info("FTP连接错误,请正确配置IP地址,账号和密码。");
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. logger.info("FTP的端口错误,请正确配置。");
  52. }
  53. return ftpClient;
  54. }
  55.  
  56. /*
  57. * 从FTP服务器下载文件
  58. *
  59. * @param ftpHost FTP IP地址
  60. *
  61. * @param ftpUserName FTP 用户名
  62. *
  63. * @param ftpPassword FTP用户名密码
  64. *
  65. * @param ftpPort FTP端口
  66. *
  67. * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
  68. *
  69. * @param localPath 下载到本地的位置 格式:H:/download
  70. *
  71. * @param txtAddress 本地文件名
  72. *
  73. * @param time 扫描时间间隔
  74. */
  75. public static void downloadFtpFile(String ftpHost, String ftpUserName,
  76. String ftpPassword, int ftpPort, String ftpPath, String localPath,
  77. String txtAddress, int time) {
  78. while(ftpPort!=21){
  79. logger.info("检测到用户输入的端口号为:"+ftpPort+",现已修改为默认值21.");
  80. ftpPort = 21;
  81. }
  82. int fs0 = 0;// 定义初始化文件的个数为零
  83. for (int a = 0; a < 500000; a++) {
  84. FTPClient ftpClient = null;
  85. try {
  86. ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword,ftpPort);
  87. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);// 设置文件类型为二进制否则可能导致乱码文件无法打开
  88. ftpClient.enterLocalPassiveMode();// 设置被动模式
  89. boolean dir = ftpClient.changeWorkingDirectory(ftpPath);
  90. // System.out.println("进入指定FTP文件夹==>"+dir);
  91. txtUtil txt = new txtUtil();
  92.  
  93. List<String> listStrings = null;
  94. try {
  95. listStrings = txt.readTxtFile(txtAddress);
  96. } catch (Exception e1) {
  97. System.out.println("警告:发现问题读取文本的时候,程序错误");
  98. e1.printStackTrace();
  99. }
  100. System.out.println("第" + (a + 1) + "次循环的listStrings长度为:"+ listStrings.size());
  101. if (dir) {
  102. File file2 = null;
  103. FTPFile[] fs = ftpClient.listFiles();
  104. if (a == 0) {
  105. for (int i = 0; i < fs.length; i++) {
  106. boolean bo = listStrings.contains(fs[i].getName());
  107. if (!bo) {
  108. if(fs[i].getName().endsWith("xml")){
  109. File file = new File(localPath);
  110. if (!file.exists() && !file.isDirectory()) {
  111. file.mkdir();
  112. logger.info("本地cim_download文件夹不存在,创建成功");
  113. }
  114. File localFile = new File(localPath
  115. + File.separatorChar + fs[i].getName());
  116. OutputStream os = new FileOutputStream(localFile);
  117. ftpClient.retrieveFile(fs[i].getName(), os);
  118. os.close();
  119. logger.info("首次启动文件复制成功:" + fs[i].getName()+ " 大小为:" + localFile.length() + "字节");
  120. txt.recordName(txtAddress, fs[i].getName());
  121. listStrings.add(fs[i].getName());
  122. }
  123. } else {
  124. logger.info("首次启动发现:<" + fs[i].getName()+ ">,本地已存在,不再复制");
  125. }
  126. }
  127. }else{
  128. for (int i = 0; i < fs.length; i++) {
  129. boolean bo = listStrings.contains(fs[i].getName());
  130. if (!bo) {
  131. if(fs[i].getName().endsWith("xml")){
  132. System.out.println("发现新文件:" + fs[i].getName());
  133. try {
  134. Thread.sleep(500);
  135. } catch (InterruptedException e) {
  136. e.printStackTrace();
  137. }
  138. file2 = new File(localPath);
  139. if (!file2.exists() && !file2.isDirectory()) {
  140. file2.mkdir();
  141. logger.info("本地cim_download文件夹可能被误删,现已创建成功");
  142. }
  143. File localFile = new File(localPath+ File.separatorChar + fs[i].getName());
  144. OutputStream os = new FileOutputStream(localFile);
  145. ftpClient.retrieveFile(fs[i].getName(), os);
  146. os.close();
  147. logger.info("新文件:" + fs[i].getName() + " 复制成功");
  148. // listStrings.add(fs[i].getName());
  149. txt.recordName(txtAddress, fs[i].getName());
  150. }
  151. }
  152. }
  153. }
  154.  
  155. fs0 = fs.length;
  156. try {
  157. System.out.println("查询第" + (a + 1) + "次时,有" + fs0+ "个文件," + "下次扫描时间为" + time + "毫秒后。");
  158. Thread.sleep(time);
  159. } catch (InterruptedException e) {
  160. e.printStackTrace();
  161. }
  162. }
  163. } catch(NullPointerException e){
  164. logger.error("NullPointerException,创建连接为空。请检查FTP服务器"+"!!!"+e.getMessage());
  165. }catch (FileNotFoundException e) {
  166. logger.error("FileNotFoundException"+e.getMessage());
  167. e.printStackTrace();
  168. } catch (SocketException e) {
  169. logger.error("连接FTP失败.");
  170. e.printStackTrace();
  171. } catch (IOException e) {
  172. e.printStackTrace();
  173. logger.error("文件读取错误。");
  174. e.printStackTrace();
  175. } catch (Exception e) {
  176. logger.error("未知异常!!!");
  177. } finally {
  178. try {
  179. close();
  180. } catch (Exception e) {
  181. logger.error("关闭FTP错误!"+e.getMessage());
  182. e.printStackTrace();
  183. }
  184. }
  185. }
  186. }
  187.  
  188. /**
  189. * 转码[GBK -> ISO-8859-1] 不同的平台需要不同的转码
  190. *
  191. * @param obj
  192. * @return
  193. */
  194. private static String gbkToIso8859(Object obj) {
  195. try {
  196. if (obj == null)
  197. return "";
  198. else
  199. return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
  200. } catch (Exception e) {
  201. return "";
  202. }
  203. }
  204.  
  205. /**
  206. * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码
  207. *
  208. * @param obj
  209. * @return
  210. */
  211. private static String iso8859ToGbk(Object obj) {
  212. try {
  213. if (obj == null)
  214. return "";
  215. else {
  216. String str = new String(obj.toString().getBytes("iso-8859-1"),
  217. "GBK");
  218. return str;
  219. }
  220. } catch (Exception e) {
  221. return "";
  222. }
  223. }
  224.  
  225. /**
  226. * 关闭当前连接
  227. */
  228. public static void close() {
  229. try {
  230. ftpClient.logout();
  231. ftpClient.disconnect();
  232. } catch (IOException e) {
  233. logger.error("ftp ftpserver close error : " + e.getMessage());
  234. }
  235. }
  236. }
  1. package cim;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileWriter;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.io.PrintWriter;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12.  
  13. public class txtUtil {
  14.  
  15. public void recordName(String txtAddress,String name) throws IOException{
  16. File file = new File(txtAddress);
  17. if(!file.exists()){
  18. file.createNewFile();
  19. }
  20. FileWriter fw = new FileWriter(file, true);
  21. PrintWriter pw = new PrintWriter(fw);
  22. pw.print(name);
  23. pw.print(",");
  24. pw.flush();
  25. try {
  26. fw.flush();
  27. pw.close();
  28. fw.close();
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33.  
  34. public List<String> readTxtFile(String txtAddress)throws Exception{
  35. List<String> list = new ArrayList<>();
  36. try {
  37. String encoding="UTF-8";
  38. File file=new File(txtAddress);
  39. if(!file.exists()){
  40. file.createNewFile();
  41. }
  42. if(file.isFile() && file.exists()){ //判断文件是否存在
  43. InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式
  44. BufferedReader bufferedReader = new BufferedReader(read);
  45. String lineTxt = null;
  46. while((lineTxt = bufferedReader.readLine()) != null){
  47. String[] sourceStrArray =lineTxt.split(",");
  48. for(int i = 0 ;i<sourceStrArray.length;i++){
  49. list.add(sourceStrArray[i]);
  50. }
  51. }
  52. read.close();
  53. }else{
  54. System.out.println("读取文件名集合出错");
  55. }
  56. }catch (Exception e) {
  57. System.out.println("读取文件内容出错");
  58. e.printStackTrace();
  59. }
  60.  
  61. return list;
  62. }
  63. }
  1. package cim;
  2.  
  3. import java.io.File;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. import javax.xml.parsers.DocumentBuilder;
  8. import javax.xml.parsers.DocumentBuilderFactory;
  9.  
  10. import org.w3c.dom.Document;
  11. import org.w3c.dom.Element;
  12. import org.w3c.dom.Node;
  13. import org.w3c.dom.NodeList;
  14.  
  15. public class ftpTest {
  16.  
  17. public static void main(String[] args) {
  18.  
  19. ftpTest test = new ftpTest();
  20. Map<String, Object> map = test.XMLReader();
  21. String ftpHost = (String) map.get("ftpHost");
  22. String ftpUserName = (String) map.get("ftpUserName");
  23. String ftpPassword = (String) map.get("ftpPassword");
  24. int ftpPort = Integer.parseInt((String) map.get("ftpPort")) ;
  25. String ftpPath = (String) map.get("ftpPath");
  26. String localPath = (String) map.get("localPath");
  27. String txtAddress = (String) map.get("txtAddress");
  28. int time = Integer.parseInt((String)map.get("time"));
  29.  
  30. FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, txtAddress,time);
  31. }
  32.  
  33. public Map<String,Object> XMLReader(){
  34. Element element = null;
  35. File f = new File("test.xml");
  36. DocumentBuilder db = null;
  37. DocumentBuilderFactory dbf = null;
  38. Map<String, Object> map = new HashMap<>();
  39. try {
  40. dbf = DocumentBuilderFactory.newInstance();
  41. db = dbf.newDocumentBuilder();
  42. Document dt = db.parse(f);
  43. element = dt.getDocumentElement();
  44. NodeList childNodes = element.getChildNodes();
  45. for (int i = 0; i < childNodes.getLength(); i++) {
  46. Node node1 = childNodes.item(i);
  47. if ("Account".equals(node1.getNodeName())) {
  48. NodeList nodeDetail = node1.getChildNodes();
  49. for (int j = 0; j < nodeDetail.getLength(); j++) {
  50. Node detail = nodeDetail.item(j);
  51. if ("ftpHost".equals(detail.getNodeName()))
  52. map.put("ftpHost", detail.getTextContent());
  53. else if ("ftpUserName".equals(detail.getNodeName()))
  54. map.put("ftpUserName", detail.getTextContent());
  55. else if ("ftpPassword".equals(detail.getNodeName()))
  56. map.put("ftpPassword", detail.getTextContent());
  57. else if ("ftpPort".equals(detail.getNodeName()))
  58. map.put("ftpPort", detail.getTextContent());
  59. else if ("ftpPath".equals(detail.getNodeName()))
  60. map.put("ftpPath", detail.getTextContent());
  61. else if ("localPath".equals(detail.getNodeName()))
  62. map.put("localPath", detail.getTextContent());
  63. else if ("txtAddress".equals(detail.getNodeName()))
  64. map.put("txtAddress", detail.getTextContent());
  65. else if ("time".equals(detail.getNodeName()))
  66. map.put("time", detail.getTextContent());
  67. }
  68. }
  69. }
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. return map;
  74. }
  75. }
  1. log4j.rootLogger=info,A1,A2
  2. # \u8F93\u51FA\u5230\u63A7\u5236\u53F0
  3. log4j.appender.A1=org.apache.log4j.ConsoleAppender
  4. log4j.appender.A1.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [\u4fe1\u606f] %m%n
  6. # \u8F93\u51FA\u5230\u6587\u4EF6\u5F53\u4E2D
  7. log4j.appender.A2=org.apache.log4j.FileAppender
  8. log4j.appender.A2.File=cim_logging.log
  9. log4j.appender.A2.Append=true
  10. log4j.appender.A2.layout=org.apache.log4j.PatternLayout
  11. log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [\u4fe1\u606f] %m%n
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <Accounts>
  3. <Account type="type1">
  4. <!-- FTP端口号 -->
  5. <ftpHost>127.0.0.1</ftpHost>
  6. <!-- FTP账号 -->
  7. <ftpUserName>1</ftpUserName>
  8. <!-- FTP密码 -->
  9. <ftpPassword>1</ftpPassword>
  10. <!-- FTP端口号 -->
  11. <ftpPort>22</ftpPort>
  12. <!-- FTP路径 -->
  13. <ftpPath>users/ems/open2000e/data/xmldat/nari/all/</ftpPath>
  14. <!-- 本地保存文件路径 -->
  15. <localPath>cim_download</localPath>
  16. <!-- 本地保存文件名集合路径 -->
  17. <txtAddress>cim_name.txt</txtAddress>
  18. <!-- 设置扫描文件的时间间隔,单位:毫秒 -->
  19. <time>5000</time>
  20. </Account>
  21. </Accounts>

是用的main方法启动。

Fat Jar打包插件方法    http://jingyan.baidu.com/article/da1091fbd7dae1027849d63b.html

下面是运行jar包

扫描FTP,保存文件的更多相关文章

  1. 解决phpstorm ftp自动保存文件问题

    初次使用phpstorm, 1.配置ftp时,远程文件要用/ftp用户名/文件夹名: 2.由于版本管理的原因(猜测),直接从本地原有文件修改时各种办法都无法上传,结果从服务器上下载一份再修改,解决这个 ...

  2. 从 FTP 服务器上下载并保存文件

    本例演示如何运用 C# 中的 FtpWebRequest 等对象从 FTP 服务器上获取文件,并结合 Stream 对象中的方法来保存下载的文件: using System; using System ...

  3. android 保存文件的各种目录列表

    一般的,我们可以通过context和Environment来获取要保存文件的目录 ($rootDir) +- /data -> Environment.getDataDirectory() | ...

  4. ftp (文件传输协议)

    ftp (文件传输协议) 锁定 本词条由“科普中国”百科科学词条编写与应用工作项目 审核 . FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议” ...

  5. [转] 三种Python下载url并保存文件的代码

    原文 三种Python下载url并保存文件的代码 利用程序自己编写下载文件挺有意思的. Python中最流行的方法就是通过Http利用urllib或者urllib2模块. 当然你也可以利用ftplib ...

  6. [java] java 实现FTP服务器文件的上传和下载

    利用Apache commons-net 实现: package com.xwolf.driver.util; import com.xwolf.driver.exception.RunExcepti ...

  7. MFC通过URL下载并保存文件代码 转载

    http://blog.csdn.net/charlessimonyi/article/details/8666108?utm_source=tuicool&utm_medium=referr ...

  8. PhpStorm 设置自动FTP同步文件

    1.添加一个FTP服务器 ① 首先在这里打开添加FTP的页面,步骤,工具栏 -> Tools -> Deployment -> Configuration .     ②添加服务器  ...

  9. ABBYY FineReader 14扫描和保存文档

    在ABBYY FineReader 14中您可以使用扫描"新建任务"窗口选项卡上的内置任务创建各种格式的数字文档.本文介绍使用FineReader 14扫描和保存文档的方法. 1. ...

随机推荐

  1. python-Generalization of Hops

    python provides a general purpose HOP,map simple form-a unary function and a collection of suitable ...

  2. CF F. MST Unification (最小生成树避圈法)

    题意 给一个无向加权联通图,没有重边和环.在这个图中可能存在多个最小生成树(MST),你可以进行以下操作:选择某条边使其权值加一,使得MST权值不变且唯一.求最少的操作次数. 分系:首先我们先要知道为 ...

  3. AES/CBC/PKCS5Padding对称加密

    package unit; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.cry ...

  4. css盒子居中

    方法1(margin: 0 auto)<!DOCTYPE html> <html lang="en"> <head> <meta char ...

  5. NodeJS 实现阿里云推送。

    虽然阿里云推送也有 NodeJS SDK ,只要在项目中引用 aliyun-sdk 就可以使用了.里面的推送功能了. 我在这里就不写怎么使用aliyun-sdk.给出来的DEMO是回调形式的.用起来有 ...

  6. (转) shell实例手册

    shell实例手册 1文件{ touch file              # 创建空白文件rm -rf 目录名           # 不提示删除非空目录(-r:递归删除 -f强制)dos2uni ...

  7. CentOS 6.5 安装MySQL数据库

    CentOS 6.5 安装MySQL数据库 [root@seeker~]# yum -y install mysql-server //安装命令 [root@seeker~]# service mys ...

  8. 121、Django rest framework入门使用

    框架介绍 为你的django平台通过model生成对应的restfull api,并可以通过对应的http接口来进行 post .get.put.delete等操作.本文是也并非入门级别,不会带你去了 ...

  9. jQuery对象和DOM对象使用说明,需要的朋友可以参考下。

    jQuery对象和DOM对象使用说明,需要的朋友可以参考下.1.jQuery对象和DOM对象第一次学习jQuery,经常分辨不清哪些是jQuery对象,哪些是 DOM对象,因此需要重点了解jQuery ...

  10. 使用request与正则表达式爬取bangumi动画排行榜

    import json import requests from requests.exceptions import RequestException import re import time d ...