1. package cn.ipanel.app.newspapers.util;
  2. import java.io.BufferedReader;
  3. import java.io.DataInputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.io.RandomAccessFile;
  9. import java.util.ArrayList;
  10. import java.util.Iterator;
  11. import java.util.List;
  12. import java.util.StringTokenizer;
  13. import org.apache.log4j.Logger;
  14. import sun.net.TelnetInputStream;
  15. import sun.net.TelnetOutputStream;
  16. import sun.net.ftp.FtpClient;
  17. /**
  18. * FTP工具类<br>
  19. * 注:上传,可上传文件、文件夹;下载,仅实现下载文件功能,不能识别子文件夹
  20. * @version 1.0.0
  21. */
  22. public class FtpUtil
  23. {
  24. private static Logger logger = Logger.getLogger(FtpUtil.class);
  25. private FtpClient ftpClient;
  26. /**
  27. * 连接FTP服务器,使用默认FTP端口
  28. * @since
  29. * @param serverIp
  30. * 服务器Ip地址
  31. * @param user
  32. * 登陆用户
  33. * @param password
  34. * 密码
  35. * @throws IOException
  36. */
  37. public void connect(String serverIp, String user, String password) throws Exception
  38. {
  39. try
  40. {
  41. // serverIp:FTP服务器的IP地址;
  42. // user:登录FTP服务器的用户名
  43. // password:登录FTP服务器的用户名的口令;
  44. ftpClient = new FtpClient();
  45. ftpClient.openServer(serverIp);
  46. ftpClient.login(user, password);
  47. // 用二进制传输数据
  48. ftpClient.binary();
  49. }
  50. catch (Exception ex)
  51. {
  52. throw new Exception(ex);
  53. }
  54. }
  55. /**
  56. * 连接ftp服务器,指定端口
  57. * @since
  58. * @param serverIp
  59. * @param port
  60. * 服务器FTP端口号
  61. * @param user
  62. * @param password
  63. * @throws IOException
  64. */
  65. public void connect(String serverIp, int port, String user, String password) throws Exception
  66. {
  67. try
  68. {
  69. // serverIp:FTP服务器的IP地址;
  70. // post:FTP服务器端口
  71. // user:登录FTP服务器的用户名
  72. // password:登录FTP服务器的用户名的口令;
  73. ftpClient = new FtpClient();
  74. ftpClient.openServer(serverIp, port);
  75. ftpClient.login(user, password);
  76. // 用2进制传输数据
  77. ftpClient.binary();
  78. }
  79. catch (Exception ex)
  80. {
  81. throw new Exception(ex);
  82. }
  83. }
  84. /**
  85. * 断开与ftp服务器的连接
  86. * @since
  87. * @throws IOException
  88. */
  89. public void disConnect() throws Exception
  90. {
  91. try
  92. {
  93. if (ftpClient != null)
  94. {
  95. ftpClient.sendServer("QUIT\r\n");
  96. ftpClient.readServerResponse();
  97. // ftpClient.closeServer();
  98. }
  99. }
  100. catch (IOException ex)
  101. {
  102. logger.error("DisConnect to FTP server failure! Detail:", ex);
  103. throw new Exception(ex);
  104. }
  105. }
  106. /**
  107. * 上传文件至FTP服务器,保持原文件名
  108. *
  109. * @throws java.lang.Exception
  110. * @return -1 文件不存在或不能读取; >0 成功上传,返回文件的大小
  111. * @param localFile
  112. * 待上传的本地文件
  113. */
  114. public long upload(File localFile) throws Exception
  115. {
  116. if (localFile == null)
  117. {
  118. return -1;
  119. }
  120. return this.upload(localFile, localFile.getName());
  121. }
  122. /**
  123. * 上传文件至FTP服务器,保持原文件名
  124. *
  125. * @throws java.lang.Exception
  126. * @return -1 文件不存在或不能读取; >0 成功上传,返回文件的大小
  127. * @param localFilePath
  128. * 待上传的本地文件路径
  129. */
  130. public long upload(String localFilePath) throws Exception
  131. {
  132. return this.upload(new File(localFilePath));
  133. }
  134. /**
  135. * 上传文件至FTP服务器,并重命名文件
  136. *
  137. * @throws java.lang.Exception
  138. * @return -1 文件不存在或不能读取; >0 成功上传,返回文件的大小
  139. * @param localFilePath
  140. * 待上传的本地文件路径
  141. * @param rename
  142. * 远程文件重命名
  143. */
  144. public long upload(String localFilePath, String rename) throws Exception
  145. {
  146. return this.upload(new File(localFilePath), rename);
  147. }
  148. /**
  149. * 上传文件至FTP服务器,并重命名文件
  150. *
  151. * @throws java.lang.Exception
  152. * @return -1 文件不存在或不能读取; >0 成功上传,返回文件的大小
  153. * @param localFile
  154. * 待上传的本地文件
  155. * @param rename
  156. * 远程文件重命名
  157. */
  158. public long upload(File localFile, String rename) throws Exception
  159. {
  160. if (localFile == null || !localFile.exists() || !localFile.canRead())
  161. {
  162. return -1;
  163. }
  164. long fileSize = localFile.length();
  165. try
  166. {
  167. if (localFile.isDirectory())
  168. {
  169. ftpClient.sendServer("XMKD " + rename + "\r\n");
  170. ftpClient.readServerResponse();
  171. File[] subFiles = localFile.listFiles();
  172. ftpClient.cd(rename);
  173. try
  174. {
  175. for (int i = 0; i < subFiles.length; i++)
  176. {
  177. fileSize += upload(subFiles[i]);
  178. }
  179. }
  180. finally
  181. {
  182. ftpClient.cdUp();
  183. }
  184. }
  185. else
  186. {
  187. this.writeFileToServer(localFile, rename);
  188. }
  189. return fileSize;
  190. }
  191. catch (Exception ex)
  192. {
  193. throw new Exception(ex);
  194. }
  195. }
  196. /**
  197. * 从ftp下载文件到本地
  198. *
  199. * @throws java.lang.Exception
  200. * @return
  201. * @param localFilePath
  202. * 本地生成的文件名
  203. * @param remoteFilePath
  204. * 服务器上的文件名
  205. */
  206. public long download(String remoteFilePath, String localFilePath) throws Exception
  207. {
  208. long result = 0;
  209. TelnetInputStream tis = null;
  210. RandomAccessFile raf = null;
  211. DataInputStream puts = null;
  212. try
  213. {
  214. tis = ftpClient.get(remoteFilePath);
  215. raf = new RandomAccessFile(new File(localFilePath), "rw");
  216. raf.seek(0);
  217. int ch;
  218. puts = new DataInputStream(tis);
  219. while ((ch = puts.read()) >= 0)
  220. {
  221. raf.write(ch);
  222. }
  223. }
  224. catch (Exception ex)
  225. {
  226. logger.error("Downloading file failure! Detail:", ex);
  227. throw new Exception(ex);
  228. }
  229. finally
  230. {
  231. try
  232. {
  233. puts.close();
  234. if (tis != null)
  235. {
  236. tis.close();
  237. }
  238. if (raf != null)
  239. {
  240. raf.close();
  241. }
  242. }
  243. catch (Exception ex)
  244. {
  245. throw new Exception(ex);
  246. }
  247. }
  248. return result;
  249. }
  250. /**
  251. * 设置FTP服务器的当前路径<br>
  252. * 可以是绝对路径,也可以是相对路径
  253. * @since
  254. * @param dirPath
  255. * 服务器文件夹路径,空代表ftp根目录
  256. * @throws IOException
  257. */
  258. public void cd(String dirPath) throws Exception
  259. {
  260. try
  261. {
  262. // path:FTP服务器上的路径,是ftp服务器下主目录的子目录
  263. if (dirPath != null && dirPath.length() > 0)
  264. {
  265. ftpClient.cd(dirPath);
  266. }
  267. }
  268. catch (Exception ex)
  269. {
  270. throw new Exception(ex);
  271. }
  272. }
  273. /**
  274. * 在服务器上创建指定路径的目录,并转到此目录
  275. * @since
  276. * @param dirPath
  277. * @throws Exception
  278. */
  279. public void mkd(String dirPath) throws Exception
  280. {
  281. try
  282. {
  283. if (dirPath != null && dirPath.length() > 0)
  284. {
  285. StringTokenizer st = new StringTokenizer(dirPath.replaceAll("\\\\", "/"), "/");
  286. String dirName = "";
  287. while (st.hasMoreElements())
  288. {
  289. dirName = (String) st.nextElement();
  290. ftpClient.sendServer("XMKD " + dirName + "\r\n");
  291. ftpClient.readServerResponse();
  292. ftpClient.cd(dirName);
  293. }
  294. }
  295. }
  296. catch (Exception ex)
  297. {
  298. throw new Exception(ex);
  299. }
  300. }
  301. /**
  302. * 删除FTP服务器目录
  303. * @since
  304. * @param directory
  305. * @throws Exception
  306. */
  307. public void rmd(String directory) throws Exception
  308. {
  309. try
  310. {
  311. if (directory != null && directory.length() > 0)
  312. {
  313. ftpClient.cd(directory);
  314. try
  315. {
  316. this.cld();
  317. }
  318. finally
  319. {
  320. ftpClient.cdUp();
  321. }
  322. ftpClient.sendServer("XRMD " + directory + "\r\n");
  323. ftpClient.readServerResponse();
  324. }
  325. }
  326. catch (Exception ex)
  327. {
  328. throw new Exception(ex);
  329. }
  330. }
  331. /**
  332. * 清空当前目录
  333. * @since
  334. * @throws Exception
  335. */
  336. public void cld() throws Exception
  337. {
  338. // 删除文件
  339. for (Iterator<String> it = getFileList().iterator(); it.hasNext();)
  340. {
  341. this.delf(it.next());
  342. }
  343. // 删除文件夹
  344. for (Iterator<String> it = getDirList().iterator(); it.hasNext();)
  345. {
  346. this.rmd(it.next());
  347. }
  348. }
  349. /**
  350. * 删除FTP服务器文件
  351. * @since
  352. * @param filePath
  353. * @throws Exception
  354. */
  355. public void delf(String filePath) throws Exception
  356. {
  357. try
  358. {
  359. if (filePath != null && filePath.length() > 0)
  360. {
  361. ftpClient.sendServer("DELE " + filePath + "\r\n");
  362. ftpClient.readServerResponse();
  363. }
  364. }
  365. catch (Exception ex)
  366. {
  367. throw new Exception(ex);
  368. }
  369. }
  370. /**
  371. * 以指定文件名,将本地文件写到FTP服务器
  372. * @since
  373. * @param localFile
  374. * 待上传的本地文件
  375. * @param fileName
  376. * 写入远程FTP服务器的文件名
  377. * @throws Exception
  378. */
  379. private void writeFileToServer(File localFile, String fileName) throws Exception {
  380. TelnetOutputStream tos = null;
  381. FileInputStream fis = new FileInputStream(localFile);
  382. try {
  383. tos = ftpClient.put(fileName);
  384. byte[] bytes = new byte[102400];
  385. int c;
  386. while ((c = fis.read(bytes)) != -1) {
  387. tos.flush();
  388. tos.write(bytes, 0, c);
  389. }
  390. } catch (Exception ex) {
  391. throw new Exception(ex);
  392. } finally {
  393. if (fis != null) {
  394. fis.close();
  395. }
  396. if (tos != null) {
  397. tos.flush();
  398. tos.close();
  399. }
  400. }
  401. }
  402. /**
  403. * 取得FTP上某个目录下的所有文件名列表
  404. *
  405. * @since
  406. * @return
  407. * @throws Exception
  408. */
  409. public List<String> getFileList() throws Exception
  410. {
  411. List<String> fileList = new ArrayList<String>();
  412. BufferedReader br = null;
  413. try
  414. {
  415. String fileItem;
  416. br = new BufferedReader(new InputStreamReader(ftpClient.list()));
  417. while ((fileItem = br.readLine()) != null)
  418. {
  419. if (fileItem.startsWith("-") && !fileItem.endsWith(".") && !fileItem.endsWith(".."))
  420. {
  421. fileList.add(parseFileName(fileItem));
  422. }
  423. }
  424. }
  425. catch (Exception ex)
  426. {
  427. logger.error("Failure to get directory list from ftp server!", ex);
  428. throw new Exception(ex);
  429. }
  430. finally
  431. {
  432. if (br != null)
  433. {
  434. try
  435. {
  436. br.close();
  437. }
  438. catch (Exception ex)
  439. {
  440. throw new Exception(ex);
  441. }
  442. }
  443. }
  444. return fileList;
  445. }
  446. /**
  447. * 取得FTP上某个目录下的所有子文件夹名列表
  448. *
  449. * @since
  450. * @return
  451. * @throws Exception
  452. */
  453. public List<String> getDirList() throws Exception
  454. {
  455. List<String> dirList = new ArrayList<String>();
  456. BufferedReader br = null;
  457. try
  458. {
  459. String fileItem;
  460. br = new BufferedReader(new InputStreamReader(ftpClient.list()));
  461. while ((fileItem = br.readLine()) != null)
  462. {
  463. if (fileItem.startsWith("d") && !fileItem.endsWith(".") && !fileItem.endsWith(".."))
  464. {
  465. dirList.add(parseFileName(fileItem));
  466. }
  467. }
  468. }
  469. catch (Exception ex)
  470. {
  471. logger.info("Failure to get directory list from ftp server!", ex);
  472. throw new Exception(ex);
  473. }
  474. finally
  475. {
  476. if (br != null)
  477. {
  478. try
  479. {
  480. br.close();
  481. }
  482. catch (Exception ex)
  483. {
  484. throw new Exception(ex);
  485. }
  486. }
  487. }
  488. return dirList;
  489. }
  490. /**
  491. * 从文件信息中解析出文件(文件夹)名
  492. *
  493. * @since
  494. * @param fileItem
  495. * @return
  496. * @throws Exception
  497. */
  498. private String parseFileName(String fileItem) throws Exception
  499. {
  500. StringTokenizer st = new StringTokenizer(fileItem);
  501. int index = 0;
  502. while (st.hasMoreTokens())
  503. {
  504. if (index < 8)
  505. {
  506. st.nextToken();
  507. }
  508. else
  509. {
  510. return st.nextToken("").trim();
  511. }
  512. index++;
  513. }
  514. return null;
  515. }
  516. /**
  517. * 上传下载测试
  518. *
  519. * @since
  520. * @param args
  521. * @throws Exception
  522. */
  523. public static void main(String[] args) throws Exception
  524. {
  525. FtpUtil ftp = new FtpUtil();
  526. try
  527. {
  528. // 连接ftp服务器
  529. ftp.connect("xx.xx.xx.xx", "ftp", "ftp");
  530. // 上传文件
  531. ftp.cd("/home/sasftp");
  532. // ftp.cld();
  533. // long fileSize = ftp.upload("D:/视频",
  534. // "xufeitewwst");
  535. // if (fileSize == -1) {
  536. // logger.info("Uploading file failure! Because file do not exists!");
  537. // } else if (fileSize == -2) {
  538. // logger.info("Uploading file failure! Because file is empty!");
  539. // } else {
  540. // logger.info("Uploading file success! File size: " + fileSize);
  541. // }
  542. // 取得bbbbbb文件夹下的所有文件列表,并下载到本地保存
  543. List<String> list = new ArrayList<String>();
  544. list.add("czybxw.txt");
  545. list.add("zjyb.txt");
  546. for (int i = 0; i < list.size(); i++)
  547. {
  548. String fileName = (String) list.get(i);
  549. System.out.println(fileName);
  550. ftp.download(fileName, "E:\\text" + File.separator + fileName);
  551. }
  552. }
  553. catch (Exception ex)
  554. {
  555. logger.error("Uploading file failure! Detail:", ex);
  556. }
  557. finally
  558. {
  559. ftp.disConnect();
  560. }
  561. }
  562. }

Java-FtpUtil工具类的更多相关文章

  1. Java Properties工具类详解

    1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...

  2. Java json工具类,jackson工具类,ObjectMapper工具类

    Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...

  3. Java日期工具类,Java时间工具类,Java时间格式化

    Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...

  4. Java并发工具类 - CountDownLatch

    Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...

  5. MinerUtil.java 爬虫工具类

    MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...

  6. MinerDB.java 数据库工具类

    MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...

  7. 小记Java时间工具类

    小记Java时间工具类 废话不多说,这里主要记录以下几个工具 两个时间只差(Data) 获取时间的格式 格式化时间 返回String 两个时间只差(String) 获取两个时间之间的日期.月份.年份 ...

  8. Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie

    Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie >>>>>>>>>>>>& ...

  9. UrlUtils工具类,Java URL工具类,Java URL链接工具类

    UrlUtils工具类,Java URL工具类,Java URL链接工具类 >>>>>>>>>>>>>>>&g ...

  10. java日期工具类DateUtil-续一

    上篇文章中,我为大家分享了下DateUtil第一版源码,但就如同文章中所说,我发现了还存在不完善的地方,所以我又做了优化和扩展. 更新日志: 1.修正当字符串日期风格为MM-dd或yyyy-MM时,若 ...

随机推荐

  1. OS X更新Catalina 10.15.2后虚拟机黑屏(已解决)

    简述 问题:更新OS X 10.15.2后VM Ware进unbuntu 16.0黑屏,但是VM Ware 有显示,情况类似如下: 解决办法   重启系统,command+r 进入恢复模式,打开bas ...

  2. vsftpd下载文件时内容乱码

    windows客户端访问Linux服务端的ftp并下载文档时,内容会出现乱码,这是由于vsftpd文件服务器不支持转码功能 通过java FTPClient下载 方法为 OutputStream is ...

  3. Java更新Oracle的clob类型字段

    Java更新Oracle的clob类型字段 1.查询该clob字段 2.处理该clob字段查询结果 3.更新该clob字段查询结果 1.查询该clob字段 <select id="se ...

  4. E.XKC's basketball team(The Preliminary Contest for ICPC Asia Xuzhou 2019)

    https://nanti.jisuanke.com/t/41387 解: 离散化+线段树. #define IOS ios_base::sync_with_stdio(0); cin.tie(0); ...

  5. python的异常处理机制

    异常机制己经成为衡量一门编程语言是否成熟的标准之一,使用异常处理机制的 Python 程序有更好的容错性,更加健壮. 对于计算机程序而言,情况就更复杂了一一没有人能保证自己写的程序永远不会出辛苦!就算 ...

  6. package[golang]学习笔记之context

    *关于context https://talks.golang.org/2014/gotham-context.slide#29

  7. Socket-实例

    import socket,os,time server = socket.socket() server.bind(("localhost",9999)) server.list ...

  8. X86逆向7:特殊窗体的破解思路

    本章我们来看两个案例,这两个案例同样使用爆破的方式破解,但是与其他的程序不同,这个程序没有弹窗,提示成功或失败使用的是图片或是一个类似图片的窗体,本章将学习两个新的API函数的使用技巧. ------ ...

  9. Spectral Norm Regularization for Improving the Generalizability of Deep Learning论文笔记

    Spectral Norm Regularization for Improving the Generalizability of Deep Learning论文笔记 2018年12月03日 00: ...

  10. Jenkins常用插件介绍

    摘要: 对于中小型运维团队,jenkins作为运维利器,可以解决很多工作中的痛点.基于UI的特性从而让使用者的入门成本很低,基于插件可以具备认证,记录,条件触发以及联动,让运维工程师可以将精力放在业务 ...